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

前端 未结 4 484
遥遥无期
遥遥无期 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 18:54

    Though @peace answer worked for him, if you do have a DBContext in your IHostedService you need to use a IServiceScopeFactory.

    To see an amazing example of how to do this check out this answer How should I inject a DbContext instance into an IHostedService?.

    If you would like to read more about it from a blog, check this out .

提交回复
热议问题