How to create parent region with default dependency injection in .NET Core?

I am creating a .NET Core console application. It periodically runs a method that does some work. How to make ServiceProvider behave the same as in ASP.NET Core applications. I want it to allow cloud services when the method starts its execution and removes the allowed services at the end of the method.

// pseudocode

globalProvider.AddScoped<ExampleService>();

// ...

using (var scopedProvider = globalProvider.CreateChildScope())
{
    var exampleService = scopedProvider.Resolve<ExampleService>();
}
+6
source share
1 answer

Link Microsoft.Extensions.DependencyInjection and create 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>();
}

You can also easily test it:

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

: .

+7

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


All Articles