Hi,
I am using .net core injection (IServiceProvider) and I wonder how can I inject IDbConnectionFactory in order to avoid using (var db = this.dbConnection.Open()) each time.
Also, what is the best life cycle recommened? AddSingleton, AddTransient, AddScoped ?
Sort code sample would be great.
Inside ServiceStack Services you don’t need to open a connection you can access the Db computed property directly, e.g:
public object Any(MyRequest request) => Db.Single<Table>(x => x.Id = request.Id);
After the request is completed when the Service is disposed it will also dispose the connection.
If you need access in a different dependency you can pass it in as an argument:
public object Any(MyRequest request) => MyRepo.GetTableById(Db, request.Id);
You’ll need use your Service Db connection if you want to utilize and of the Multitenancy features or fetch the connection from HostContext.AppHost.GetDbConnection(Request) manually.
Alternatively you can have a base class with a lazy property which is similar to how ServiceStack Services work, this is the implementation of ServiceStack’s RepositoryBase class:
public abstract class RepositoryBase : IDisposable, IRepository
{
public virtual IDbConnectionFactory DbFactory { get; set; }
IDbConnection db;
public virtual IDbConnection Db => db ?? (db = DbFactory.OpenDbConnection());
public virtual void Dispose() => db?.Dispose();
}
So your classes that need data access can also access the lazy Db property, e.g:
public MyRepo : RepositoryBase
{
public Table GetTableById(int id) => Db.SingleById<Table>(id);
}
As the IDbConnection is not threadsafe it should be registered as transient, only the IDbConnectionFactory should be registered as a singleton.
The lazy property approach in RepositoryBase still applies only that you’d need to use constructor injection since .net core DI doesn’t support property injection.
Otherwise you can use transient scope I just don’t like the lifecycle of important pooled resources left to a DI, inside a ServiceStack Service it’s disposed of immediately after the Service is executed so it’s returned to the pool immediately instead of whenever the DI disposes it.