Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>(); } 
like image 794
x2bool Avatar asked May 01 '17 16:05

x2bool


People also ask

What is default dependency injection in .NET Core?

Dependency Injection is the design pattern that helps us to create an application which loosely coupled. This means that objects should only have those dependencies that are required to complete tasks.

What is difference between Addtransient and AddScoped and Addsingleton?

Singleton is a single instance for the lifetime of the application domain. Scoped is a single instance for the duration of the scoped request, which means per HTTP request in ASP.NET. Transient is a single instance per code request.

How can you create your own scope for a scoped object in net?

You can inject a ServiceScopyFactory in the class that reacts to messages from the queue, then for each message it receives it can create a scope, from which it requests a MessageHandler dependency.


1 Answers

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.

like image 200
Ilya Chumakov Avatar answered Oct 14 '22 21:10

Ilya Chumakov