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

  • Avatar photo
  • 2023年10月24日

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: