I have a .NET 5 background worker applications with a single background service (MyInternalBackgroundService).
Now I am working on a modular plug in architecture where plug ins are put in a plug in directory, from there assemblies are loaded. Each assembliy can contain multiple class definitons which inherit from BackgroundService. I load the list of types that are inheriting from BackgroundService.
I just can't figure out how to call the AddHostedService method for the loaded types. Every approach seems to cause a different compiler error.
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyInternalBackgroundServiceImplementation>();
TypeInfo[] moduleTypes = // class scanning directories for dlls, load the assemblies and find the desired types
foreach(var moduleType in moduleTypes)
{
// can't find the correct way
// services.AddHostedService<moduleType>();
//services.AddHostedService<moduleType.GetType()>();
}
});
CodePudding user response:
Internally AddHostedService
looks like this
Further AddTransient
looks like this
So you can try the following approach (of course as long as TypeInfoObjectHere
implements IHostedService
) services.AddTransient(typeof(IHostedService), TypeInfoObjectHere);