Search code examples
dependency-injectionmicroservicesbackground-serviceihostedservice

C# HostedService through IHost - get Instance from running ServicePool


The question is quite simple, yet challenging.

Normal service creation:

IHost host = Host.CreateDefaultBuilder(args)
                                .ConfigureServices(services =>
                                {
                                    services.AddHostedService<WorkerA>();
                                    services.AddHostedService<WorkerB>();
                                })
                                .Build();

await host.RunAsync();

Now, is it possible for WorkerB to get the "Instance" of WorkerA to Execute a Method, retrieve a properties, etc. ? Yet, is there a "global" ServiceCollection or Servicepool to query on and retrieve the instances of it?


Solution

  • You can do the following:

    services.AddSingleton<IHostedService, WorkerA>();
    services.AddSingleton<IHostedService, WorkerB>();
    

    Now WorkerB can be injected with WorkerA in its constructor, while its guaranteed that WorkerB gets the same instance as ASP.NET Core is using as a hosted service.

    A better solution, though, is to extract the shared logic that is both used by WorkerA and WorkerB from WorkerA into a new service, and inject that into both WorkerA and WorkerB.

    Do note that both workers might access the same logic in parallel, so you need to make sure that this shared code is thread safe.