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.

Leave a Comment