How is a Scoped service instance handled in a .NET Core Console application?

I copied this from ConfigureServices in the web application being created, where I am trying to get off the network and use only the console application or service:

 serviceCollection.AddScoped<IDbConnection, SqlConnection>(c => new SqlConnection(App.Configuration.GetConnectionString("DefaultConnection"))); 

The console application works great, but I wonder how the connection lifetime is handled. If and when is the connection closed or located? Or does it behave the same as a transitional instance, and I have to dispose of it myself?

+5
source share
1 answer

When you create an IServiceProvider from the IServiceCollection ( BuildServiceProvider method), and you use this instance of IServiceProvider to resolve IDbConnection , you will receive the same instance of IDbConnection every time. The binding area is associated with IServiceProvider . to create a new scope that you need to allow from the IServiceScopeFactory container, and use it to create an IServiceProvider that has a scope:

 using (var scope = scopeFactory.CreateScope()) { var scopedConnection = scope.ServiceProvider.GetRequiredService<IDbConnection>(); } 

The connection will be selected when the area is deleted.

The ASP Core areas are managed by middleware for you, which creates a new scope, and then uses the IServiceProvider attached to that area to allow the controller and everything in this web request. In a console application, you need to manage areas yourself.

+6
source

Source: https://habr.com/ru/post/1269405/


All Articles