Description
I 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() 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