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