jeudi 16 mars 2023

.NET 6 Is it possible to scan the background services and invoke AddHostedService

I am now using .NET 6 Worker Service to develop an backend service, and I have multi background services need to be registered by AddHostedService<> like:

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService<WorkerA>();
        services.AddHostedService<WorkerB>();
        services.AddHostedService<WorkerC>();
    })
    .Build();

await host.RunAsync();

I want to find a better way to register background services dynamically, for example:

var workers = Assembly.GetExecutingAssembly().GetTypes()
    .Where(worker =>
        worker is {IsClass: true, IsAbstract: false} &&
        !string.IsNullOrWhiteSpace(worker.Namespace) &&
        worker.Namespace.Equals(typeof(BaseWorker).Namespace))
    .ToArray();

foreach (var worker in workers)
{
    // Incorrect here
    services.AddHostedService<worker>();
}

However I failed since the worker is a Type not a class name. Could someone give me some instructions, thank you.





Aucun commentaire:

Enregistrer un commentaire