问题
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