简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM