Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i access IServiceCollection from a background thread

I am trying to perform some long running operations in the background. These operations would need access to some services that have been registered with ServiceCollection in Startup.cs.

I am injecting IServiceProvider to the class that is going to spawn a background thread.

public WorkflowService(IServiceProvider serviceProvider)
{
    _serviceProvider = serviceProvider;
}

(Note, i cannot inject individual services because i don't know before-hand which component is going to be invoked and which services each component will require).

I am then passing _serviceProvider to the method that will be executed in the background.

Task task = new Task(() => ExecuteStep(firstStep, workflowInstanceId, workflowMetadata, _serviceProvider));
task.Start();

Ths issue is that by the time i try to resolve a service on the background thread, IServiceProvider has been disposed and i get an exception.

object service = _serviceProvider.GetRequiredService(item.GetType());

In ASP.NET 4.5, i could have achieved something similar by using GlobalConfiguration.Configuration.DependencyResolver, but i am unable to find something equivalent in Core 2.2 or figure out the right way to achieve this.

using (var scope = GlobalConfiguration.Configuration.DependencyResolver.BeginScope())
{

....
     //Obtain the Type from the DI container
     object service = scope.GetService(serviceType);
....
}
like image 502
Nauzad Kapadia Avatar asked Nov 27 '25 02:11

Nauzad Kapadia


1 Answers

You should use BackgroundService for background tasks.

Anyway, you can create new scope with IServiceScopeFactory:

public WorkflowService(IServiceScopeFactory serviceProviderFactory)
{
    var scope = serviceProviderFactory.CreateScope();
    _serviceProvider = scope.ServiceProvider;
}
like image 197
cem Avatar answered Nov 29 '25 15:11

cem