[.net 7] Inject HostedService into another HostedService?
See original GitHub issueI have two Services: ServiceA and ServiceB. Both derive from BackgroundService and are added as such to the builder in Program.cs
var builder = WebApplication.CreateBuilder(args);
var config = builder.Configuration;
builder.Services.AddHostedService<ServiceA>();
builder.Services.AddHostedService<ServiceB>();
ServiceB needs access to ServiceA instance, so that it can queue tasks that ServiceA needs to perform. I’m trying to inject ServiceA into ServiceB, but keep getting into issues.
- Tried constructor DI approach but it results in an exception at startup.
System.AggregateException: ‘Some services are not able to be constructed (Error while validating the service descriptor ‘ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: MyProject.ServiceB’: Unable to resolve service for type ‘MyProject.ServiceA’ while attempting to activate ‘MyProject.ServiceB’.)’
- Tried using IServiceProvider to GetService<ServiceA>() in constructor of ServiceB and also in ExecuteAsync method of ServiceB, but in both cases, GetService returns null.
While researching, I finally came upon this answer (read last line), which seems to suggest AddHostedService instances cannot be used in DI? https://stackoverflow.com/a/74376651/934257
Issue Analytics
- State:
- Created 10 months ago
- Reactions:1
- Comments:12 (7 by maintainers)

Top Related StackOverflow Question
Would be helpful, if this was added in Hosted Service or AddHostedService documentation. I had to spent hours to figure out this solution.
Out of interest: can you share more info why this design is needed? That coupling is IMO a bad choice – but I don’t know your requirements, so aplogize the “bad” (and I don’t try to push you in another direction again 😉). Can something like https://github.com/jbogard/MediatR work for it.