Cannot consume scoped service 'MyDbContext' from singleton 'Microsoft.AspNetCore.Hosting.Internal.HostedServiceExecutor'

前端 未结 4 492
遥遥无期
遥遥无期 2021-01-07 18:21

I\'ve build a background task in my ASP.NET Core 2.1 following this tutorial: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-

4条回答
  •  庸人自扰
    2021-01-07 19:03

    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();
    }
    

    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();
    }
    

    The second way internally just resolves IServiceProviderScopeFactory and basically does the very same thing.

提交回复
热议问题