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-
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 .
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.
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.
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.