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);
....
}
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;
}
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