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

前端 未结 4 459
遥遥无期
遥遥无期 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 .

    0 讨论(0)
  • 2021-01-07 18:57

    You still need to register MyDbContext with the service provider. Usually this is done like so:

    services.AddDbContext<MyDbContext>(options => {
        // Your options here, usually:
        options.UseSqlServer("YourConnectionStringHere");
    });
    

    If you also posted your Program.cs and Startup.cs files, it may shed some more light on things, as I was able to quickly setup a test project implementing the code and was unable to reproduce your issue.

    0 讨论(0)
  • 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<MyDbContext>();
    }
    

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

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

    0 讨论(0)
  • 2021-01-07 19:06

    I found the reason of an error. It was the CoordinatesHelper class, which is used in the the background task OnlineTaggerMS and is a Transient - so it resulted with an error. I have no idea why compilator kept throwing errors pointing at MyDbContext, keeping me off track for few hours.

    0 讨论(0)
提交回复
热议问题