Hosted services are registered as singletons, and cannot directly depend on scoped services. If an instance of a scoped services was injected into a singleton service, it would become a singleton itself.
Captive Dependency[
^]
The dangers and gotchas of using scoped services in IConfigureOptions[
^]
Your
Worker
class
(which you haven't shown) takes a direct dependency on a scoped service - presumably the Entity Framework context.
The documentation has an example of working around this limitation:
Background tasks with hosted services in ASP.NET Core | Microsoft Docs[
^]
Essentially, you inject an
IServiceScopeFactory
into your singleton service. When you need a scoped service, you create a scope and resolve the service from that:
public class MySingletonService
{
private IServiceScopeFactory Services { get; }
public MySingletonService(IServiceScopeFactory services)
{
Services = services;
}
public void DoSomethingWithScopedService()
{
using (var scope = Services.CreateScope())
{
var myScopedService = scope.GetRequiredService<IScopedService>();
}
}
}
(The Microsoft example injects
IServiceProvider
, but
IServiceScopeFactory
is more appropriate, since you only need the
CreateScope
method.)
NB: This is not pure "DI", because the dependencies of the singleton service are hidden within the implementation. Some people will call this the "service locator anti-pattern". But as far as I can see, it's about your only option for using a scoped service from a singleton.