I copied this from ConfigureServices
in a web application I'm building, where I'm trying to move away from the web and only use a console app or service:
serviceCollection.AddScoped<IDbConnection, SqlConnection>(c => new SqlConnection(App.Configuration.GetConnectionString("DefaultConnection")));
The console app works fine, but I'm wondering how the lifetime of the connection is handled. If and when is the connection closed and or disposed? Or does this behave the same as a transient instance, and I should dispose it myself?
When you build IServiceProvider
from IServiceCollection
(BuildServiceProvider
method) and you use this instance of IServiceProvider
to resolve IDbConnection
you will get same instance of IDbConnection
every time. Scope is connected to IServiceProvider
. to create new scope you need to resolve from the container IServiceScopeFactory
and use it to create IServiceProvider
that is scoped:
using (var scope = scopeFactory.CreateScope())
{
var scopedConnection = scope.ServiceProvider.GetRequiredService<IDbConnection>();
}
Connection will be disposed when scope is disposed.
In ASP Core scopes are managed for you by middleware which creates new scope and then uses IServiceProvider
attached to this scope to resolve Controller and everything within this web request. In console application you need to manage scopes yourself.