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>(); }
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With