经验分享 · 2023年10月24日

Solved Cannot consume scoped service ‘DataModel.MyDbContext’ from singleton ‘Microsoft.Extensions.Hosting.IHostedService’.”

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.

 

It’s perfectly fine to just inject IServiceProvider and do the following when you need the scoped service: