-
-
Save christiannagel/dbe3cee36cb9fef1976f964d1b840711 to your computer and use it in GitHub Desktop.
Creating multiple scopes in a console application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static void UsingScoped() | |
{ | |
Console.WriteLine(nameof(UsingScoped)); | |
ServiceProvider RegisterServices() | |
{ | |
var services = new ServiceCollection(); | |
services.AddSingleton<INumberService, NumberService>(); | |
services.AddScoped<IServiceA, ServiceA>(); | |
services.AddSingleton<IServiceB, ServiceB>(); | |
services.AddTransient<IServiceC, ServiceC>(); | |
return services.BuildServiceProvider(); | |
} | |
using (ServiceProvider container = RegisterServices()) | |
{ | |
using (IServiceScope scope1 = container.CreateScope()) | |
{ | |
IServiceA a1 = scope1.ServiceProvider.GetService<IServiceA>(); | |
a1.A(); | |
IServiceA a2 = scope1.ServiceProvider.GetService<IServiceA>(); | |
a2.A(); | |
IServiceB b1 = scope1.ServiceProvider.GetService<IServiceB>(); | |
b1.B(); | |
IServiceC c1 = scope1.ServiceProvider.GetService<IServiceC>(); | |
c1.C(); | |
IServiceC c2 = scope1.ServiceProvider.GetService<IServiceC>(); | |
c2.C(); | |
} | |
Console.WriteLine("end of scope1"); | |
using (IServiceScope scope2 = container.CreateScope()) | |
{ | |
IServiceA a3 = scope2.ServiceProvider.GetService<IServiceA>(); | |
a3.A(); | |
IServiceB b2 = scope2.ServiceProvider.GetService<IServiceB>(); | |
b2.B(); | |
IServiceC c3 = scope2.ServiceProvider.GetService<IServiceC>(); | |
c3.C(); | |
} | |
Console.WriteLine("end of scope2"); | |
Console.WriteLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment