How to create a child scope from the parent with default dependency injection in .NET Core?

浪尽此生 提交于 2020-07-05 05:26:31

问题


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>();
}

回答1:


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);
}

Documentation: Service Lifetimes and Registration Options.

Reference Microsoft.Extensions.DependencyInjection or just Microsoft.AspNetCore.All package to use the code above.



来源:https://stackoverflow.com/questions/43722463/how-to-create-a-child-scope-from-the-parent-with-default-dependency-injection-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!