In my scenerio, I want to inject the linq2db scoped service to a service which inherited from IHostedService, then got the error.
We need to inject IServiceScopeFactory to generate a scope. Otherwise we are not able to resolve scoped services in a singleton.
1 2 3 4 |
using (var scope = serviceScopeFactory.CreateScope()) { var context = scope.ServiceProvider.GetService<MyDbContext>(); } |
It’s perfectly fine to just inject IServiceProvider
and do the following when you need the scoped service:
1 2 3 4 |
using (var scope = serviceProvider.CreateScope()) // this will use `IServiceScopeFactory` internally { var context = scope.ServiceProvider.GetService<MyDbContext>(); } |