I have a .Net core (v2.2) API. That API uses some external service calls. We want to make them as fire and forget calls. We used .net core Background service to implement that. We have multiple background services. Now if I register all those IHostedService in Dependency Injection, The last registered background service works, and others come as null in constructor injection of project. Registering dependencies like:
services.AddHostedService<BackgroundServiceA>();
services.AddHostedService<BackgroundServiceB>();
And also, I tried adding them as:
services.AddSingleton<IHostedService, BackgroundServiceA>();
services.AddSingleton<IHostedService, BackgroundServiceB>();
In both the cases, only BackgroundServiceB works, BackgroundServiceA comes as null in constructor injection.
To handle this, I was using ServiceProvider to get the object.
var services = serviceProvider.GetServices<IHostedService>();
_backgroundServiceA = services.First(o => o.GetType() == typeof(BackgroundServiceA)) as BackgroundServiceA;
Is it a good way to handle such an issue or I am missing something while registering dependencies.
Also, can we trigger both the background calls parallel?