.net.net-7.0ihostedservice

Add Multiple Hosted Services with different concrete types


I have the following constructor definition for my class:

public MyWorkerService(IConfiguration configuration, ILogger<MyWorkerService> logger, IWorkerService workerSerice)

I then have the following code to create a hosted service:

builder.Host.ConfigureServices(services =>
{
    services.AddHostedService<MyWorkerService>();
});

This works great as I only have one implementation of IWorkerService. I now want two implementations of IWorkerService that both run.

I have tried the following:

builder.Services.AddHostedService(sp => new MyWorkerService(configuration, sp.GetRequiredService<ILogger<MyWorkerService>>(), sp.GetRequiredService<WorkerServiceA>()));
builder.Services.AddHostedService(sp => new MyWorkerService(configuration, sp.GetRequiredService<ILogger<MyWorkerService>>(), sp.GetRequiredService<WorkerServiceB>()));

WorkerServiceA is being called, WorkerServiceB is not. What am I doing wrong?


Solution

  • It looks like this is a design decision https://github.com/dotnet/runtime/issues/38751.

    My round is to use generics to make unique names.

    public class MyWorkerService<T> : IHostedService where T : IWorkerService 
    
    public MyWorkerService(IConfiguration configuration, ILogger<MyWorkerService<T>> logger, T workerSerice) 
    

    I can then use this:

    builder.Services.AddHostedService(sp => new MyWorkerService<WorkerServiceA>(configuration, sp.GetRequiredService<ILogger<MyWorkerService<WorkerServiceA>>>(), sp.GetRequiredService<WorkerServiceA>()));
    builder.Services.AddHostedService(sp => new MyWorkerService<WorkerServiceB>(configuration, sp.GetRequiredService<ILogger<MyWorkerService<WorkerServiceB>>>(), sp.GetRequiredService<WorkerServiceB>()));