Cannot consume scoped service 'MyDbContext' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'
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<MyDbContext>();
}
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<MyDbContext>();
}
The second way internally just resolves IServiceProviderScopeFactory
and basically does the very same thing.
Though @peace answer worked for him, if you do have a DBContext in your IHostedService
you need to use a IServiceScopeFactory
.
To see an amazing example of how to do this check out this answer How should I inject a DbContext instance into an IHostedService?.
If you would like to read more about it from a blog, check this out .
I found the reason of an error. It was the CoordinatesHelper
class, which is used in the the background task OnlineTaggerMS
and is a Transient
- so it resulted with an error. I have no idea why compilator kept throwing errors pointing at MyDbContext
, keeping me off track for few hours.