Skip to content

[.net 7] Inject HostedService into another HostedService? #45071

Open
@AachoLoya

Description

@AachoLoya

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.

  1. 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'.)'

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

Metadata

Metadata

Assignees

Labels

DocsThis issue tracks updating documentationarea-networkingIncludes servers, yarp, json patch, bedrock, websockets, http client factory, and http abstractionsnet8_docathonThis issue is part of the documentation push in Fall 2023.

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions