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?
ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. For more information specific to dependency injection within MVC controllers, see Dependency injection into controllers in ASP.NET Core.
In Asp.Net Core a new service scope will be created at each request and will be disposed when request ended with a response or an exception. A scoped service is requested; Service scope will create an instance of the service that has not been already created in the service scope.
In a scoped service, with every HTTP request, we get a new instance. However, within the same HTTP request, if the service is required in multiple places, like in the view and in the controller, then the same instance is provided for the entire scope of that HTTP request.
Use Transient lifetime for the lightweight service with little or no state. Scoped services service is the better option when you want to maintain state within a request. Singletons are created only once and not destroyed until the end of the Application. Any memory leaks in these services will build up over time.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With