[英]How is a Scoped service instance handled in a .NET Core Console application?
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: 我在我正在构建的Web应用程序中从
ConfigureServices
复制了这个,我试图远离Web,只使用控制台应用程序或服务:
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. 当您从
IServiceCollection
( BuildServiceProvider
方法)构建IServiceProvider
并使用此IServiceProvider
实例来解析IDbConnection
,每次都会获得相同的IDbConnection
实例。 Scope is connected to IServiceProvider
. Scope连接到
IServiceProvider
。 to create new scope you need to resolve from the container IServiceScopeFactory
and use it to create IServiceProvider
that is scoped: 要创建新的作用域,您需要从容器
IServiceScopeFactory
解析并使用它来创建作用域的IServiceProvider
:
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. 在ASP Core中,中间件为您管理范围,创建新范围,然后使用附加到此范围的
IServiceProvider
来解析Controller和此Web请求中的所有内容。 In console application you need to manage scopes yourself. 在控制台应用程序中,您需要自己管理范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.