Search code examples
.net-corewindows-servicesservice-workerasp.net-core-hosted-services

Register Hosted Services based on Configuration in .NET Core Worker services


In .NET core 3+ worker service we can register multiple worker services using the ConfigureServices under the CreateHostBuilder method as below

Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
   services.AddHostedService<TestWorker1>();
   services.AddHostedService<TestWorker2>();
});

Is there a way to add these services (TestWorker1,TestWorker2), based on a configuration setting (e.g. appsettings.json), So that only services that are defined in the config file are registered.

Any other generic approach's other than the config file approach are also welcome.

Thanks in advance.


Solution

  • You can do something like this where you can read your configuration from any IConfiguration.

    Ignore the config["HostedServices"] = "worker1"; it is just for testing purpose.

            var config = new ConfigurationBuilder()
                            .AddJsonFile("appsettings.json", optional: true)
                            .AddInMemoryCollection()
                            .Build();
    
            config["HostedServices"] = "worker1";
            // config["HostedServices"] = "worker1,worker2";
    
            var hostBuilder = Host.CreateDefaultBuilder(args)
                .ConfigureServices((hostContext, services) =>
                {
                    var workersString = config.GetValue<string>("HostedServices");
                    var workers = workersString.Split(",");
                    if(workers.Contains("worker1"))
                    {
                        services.AddHostedService<Worker1>();
                    }
                    if(workers.Contains("worker2"))
                    {
                        services.AddHostedService<Worker2>();
                    }
    
                }).ConfigureLogging(b => {
                    b.AddConsole();
                    b.SetMinimumLevel(LogLevel.Information);
                });
    
            using(var host = hostBuilder.Build())
            {
                await host.StartAsync();
                await host.StopAsync();
            }
    

    A full example where you can test can be found in this netfiddle