Override lifetime in ASP.NET Core Dependency Injection

I registered the Entity Framework DBContext using standard code:

public void ConfigureServices(IServiceCollection services) { [...] services.AddDbContext<MyDbContextType>(ServiceLifetime.Scoped); } 

And this is great for services called from controllers that require EF services.

However, I have a few controllers that are special. They run jobs on new threads that expire throughout the life of the web request. When these jobs use my DbContext (or use services that use my DbContext), an error occurs because the scope instance has already been deleted.

Is there a way to override the life of my embedded DbContext for specific controllers only? Or is there another solution you could offer?

+5
source share
1 answer

You should not override this behavior. Instead, the code that you run in the background thread should work in its own area. This means that the first thing the background thread does is create a new IServiceScope using IServiceScopeFactory . From this area, you authorize the service that you want to use, and you call this service. At the end of the operation, you position your volume.

For instance:

 private IServiceScopeFactory factory; new Thread(() => { using (var scope = this.factory.CreateScope()) { // Resolve var service = scope.ServiceProvider.GetRequiredService<IService>(); // Use service.DoStuff(); // Dispose scope } }).Start(); 

For more information on working with DI in multi-threaded applications, see this documentation . Although the documentation is written for a specific DI container, it is general in nature and the tip also applies to your DI container.

+8
source

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


All Articles