mardi 16 novembre 2021

How to register all Hosted Services with reflection in dotnet 5.0

I'm trying to register all my worker services as Hosted service in dotnet 5.0 with reflection.

I've already registered all my project's application services in this way :

private static void RegisterApplicationServices(IServiceCollection services)
    {
        
        var applicationServices = (Assembly.GetAssembly(typeof(ConfigurationService)))
                              .GetTypes()
                              .Where(x => !x.IsInterface &&
                              x.GetInterface(typeof(IApplicationService).Name) != null);

        foreach (var serviceType in applicationServices)
        {
            var type = serviceType.UnderlyingSystemType;
            services.AddTransient(type.GetInterface($"I{type.Name}"), type);
        }

    }

But when it comes to Hosted service it doesn't work. I need some way to register all workers as Hosted services.

        services.AddHostedService<WokrerService1>();
        services.AddHostedService<WokrerService2>();
        services.AddHostedService<WokrerService3>();
        services.AddHostedService<WokrerService4>();
        services.AddHostedService<WokrerService5>();
        services.AddHostedService<WokrerService6>();

private static void RegisterHostedServices(IServiceCollection services)
{
        //What should I do here?
}

All the workers inherit from a BaseWorker class

   public abstract class BaseWorkerService<TWorkerService> :
         BackgroundService, IAppHostedService where TWorkerService : class
   {

   }
    public class TransactionSubscriberService :
                BaseWorkerService<TransactionSubscriberService>
   {

   }

I appreciate any help.





Aucun commentaire:

Enregistrer un commentaire