I\'ve build a background task in my ASP.NET Core 2.1 following this tutorial: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-
You need to inject IServiceScopeFactory to generate a scope. Otherwise you are not able to resolve scoped services in a singleton.
using (var scope = serviceScopeFactory.CreateScope())
{
var context = scope.ServiceProvider.GetService();
}
Edit:
It's perfectly fine to just inject IServiceProvider and do the following:
using (var scope = serviceProvider.CreateScope()) // this will use `IServiceScopeFactory` internally
{
var context = scope.ServiceProvider.GetService();
}
The second way internally just resolves IServiceProviderScopeFactory and basically does the very same thing.