mercredi 13 octobre 2021

AddHostedService for Types that are loaded from dynamically loaded assemblies

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()>();
      }
    });




Aucun commentaire:

Enregistrer un commentaire