dotnet / dotnet/aspnetcore

[.net 7] Inject HostedService into another HostedService?

Open
#45,071 12 comments 2 reactions 1 assignee Claimed by @benjaminpetit View on GitHub
area-networking Docs net8_docathon
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

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();
builder.Services.AddHostedService();
```

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

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.