如何使用.NET Core中的默认依赖项注入从父级创建子级作用域? [英] How to create a child scope from the parent with default dependency injection in .NET Core?
问题描述
我正在构建一个控制台.NET Core应用程序.它定期运行可以完成某些工作的方法.如何使ServiceProvider的行为与在ASP.NET Core应用程序中的行为相同.我希望它在方法开始执行时解析作用域服务,并在方法结束时处置已解析的服务.
I am building a console .NET Core application. It periodically runs a method that does some work. How do I make ServiceProvider behave in the same way it behaves in ASP.NET Core apps. I want it to resolve scoped services when the method begins it's execution and dispose the resolved services at the end of the method.
// pseudocode
globalProvider.AddScoped<ExampleService>();
// ...
using (var scopedProvider = globalProvider.CreateChildScope())
{
var exampleService = scopedProvider.Resolve<ExampleService>();
}
推荐答案
使用IServiceProvider.CreateScope()
方法创建本地范围:
Use IServiceProvider.CreateScope()
method to create a local scope:
var services = new ServiceCollection();
services.AddScoped<ExampleService>();
var globalProvider = services.BuildServiceProvider();
using (var scope = globalProvider.CreateScope())
{
var localScoped = scope.ServiceProvider.GetService<ExampleService>();
var globalScoped = globalProvider.GetService<ExampleService>();
}
可以很容易地对其进行测试:
It can be easily tested:
using (var scope = globalProvider.CreateScope())
{
var localScopedV1 = scope.ServiceProvider.GetService<ExampleService>();
var localScopedV2 = scope.ServiceProvider.GetService<ExampleService>();
Assert.Equal(localScopedV1, localScopedV2);
var globalScoped = globalProvider.GetService<ExampleService>();
Assert.NotEqual(localScopedV1, globalScoped);
Assert.NotEqual(localScopedV2, globalScoped);
}
文档:服务寿命和注册选项.
参考 Microsoft.Extensions.DependencyInjection 或只是 Microsoft.AspNetCore.All 包以使用上面的代码.
Reference Microsoft.Extensions.DependencyInjection or just Microsoft.AspNetCore.All package to use the code above.
这篇关于如何使用.NET Core中的默认依赖项注入从父级创建子级作用域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!