Search code examples
c#.netbackground-serviceworker-service

Configuration section for each worker service


Good day all, I am trying to host two BackgroundService instances in a single IHost and provide them different configuration sections. Unfortunately I cant seem to find a way to do it other than going for the options pattern. here is what my IHost looks like

IHost host = Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostBuilderContext, configurationBuilder) =>
        {
            configurationBuilder.Sources.Clear();
            configurationBuilder.Add(configurationHelperSource);
        })
        .ConfigureLogging((hostBuilderContext, loggingBuilder) =>
        {
            loggingBuilder.ClearProviders();
            loggingBuilder.AddProvider(logHelperProvider);
        })
        .UseWindowsService()
        .ConfigureServices((hostContext, services) =>
        {
            services.AddHostedService<ProcessPendingEmails>();
            services.AddHostedService<LoadFilesToDatabase>();
        })
        .Build();

    host.Run();

I wish for both of these services to get different IConfiguration sections. Hoping for some help here. Cheers

tried other stackoverflow questions, msdn and I was looking to avoid using the IOptions pattern


Solution

  • The .Net Configuration system is based on key and value pairs. You are not forced to create classes to map individual values if you don't want to.

    Simply inject IConfiguration and read the configuration values by querying using the key.

    From this Microsoft page:

    // Ask the service provider for the configuration abstraction.
    IConfiguration config = host.Services.GetRequiredService<IConfiguration>();
    
    // Get values from the config given their key and their target type.
    int keyOneValue = config.GetValue<int>("KeyOne");
    bool keyTwoValue = config.GetValue<bool>("KeyTwo");
    string? keyThreeNestedValue = config.GetValue<string>("KeyThree:Message");
    

    Just do the same, except maybe for using GetRequiredService. Instead just ask for IConfiguration in the services' constructors.