0

This service I am working on has two service types, lets call them A and B.

I know I could start both services within the same .exe by doing

IHostedService.AddHostedService<A>();
IHostedService.AddHostedService<B>();

But I want to keep the services working separately. Is there any way to call AddHostedService dynamically? I mean getting the service type via the appsettings, and doing something like this. I am simplifying the code, but imagine I am getting the string A from the appsettings:

var type = Type.GetType("A");
IHostedService.AddHostedService<Type>();
  • You could get this working via reflection, but maybe a factory approach would work better – Jonesopolis Jun 22 '22 at 14:35
  • You can try using approach with service descriptors similar to what is done in second duplicate. – Guru Stron Jun 22 '22 at 14:38
  • Be aware that `AddHostedService` is just a helper method: https://github.com/dotnet/aspnetcore/blob/2c1376c95ff46b0870d323ee5c5b064af263062e/src/Microsoft.Extensions.Hosting.Abstractions/ServiceCollectionHostedServiceExtensions.cs so you could just write `services.AddTransient(typeof(IHostedService), Type.GetType("A"));` – ProgrammingLlama Jun 22 '22 at 14:44
  • @GuruStron I just saw that duplicate. Will try that and update if that works. – Salvador Abate Jun 22 '22 at 14:47
  • @jonathan I don't think those other questions are really good solutions when there's a much simpler solution. – ProgrammingLlama Jun 22 '22 at 14:48
  • @Jonesopolis second one was added by me) – Guru Stron Jun 22 '22 at 14:49
  • @DiplomacyNotWar also `AddHostedService` is using `Singleton` lifetime - ` services.TryAddEnumerable(ServiceDescriptor.Singleton());` – Guru Stron Jun 22 '22 at 14:51
  • @guru not according to the code I linked above. Ah, maybe that's the old repository. I'm on my phone so it's difficult to check. I'll take your word for it, though my point still stands if OP uses `AddSingleton` – ProgrammingLlama Jun 22 '22 at 14:52
  • 2
    @DiplomacyNotWar interesting. Maybe it was changed. source.dot.net [shows singleton](https://source.dot.net/#Microsoft.Extensions.Hosting.Abstractions/ServiceCollectionHostedServiceExtensions.cs,7a9ac7b282b7b4d3) also. And the code you have shared is not present in main/7.0-preview branches. – Guru Stron Jun 22 '22 at 14:54

0 Answers0