C#C
C#3y ago
zobweyt

✅ What is the best way to setup app configuration using IHostBuilder?

I want to make a good building of my host configuration and make it convenient to use. My goal is to get the as much as possible:
  • Convenience;
  • Strongly typing;
  • Won't compile against typos in keys;
I've already tried those ways to setup configuration and found them inconvenient:
  1. HostBuilderContext.Configuration["Key"] · hardcoding keys;
  2. context.Configuration.Get<Configuration>() · calling the same method everywhere;
  3. context.Configuration.Bind(configuration) · confusing where to bind it at the first time;
Personally I'm using the third way, because it saves me from code duplication and hardcoding keys, but also brings a new problem — confusing where to bind the configuration.

Currently, I'm binding it in the IHostBuilder.ConfigureAppConfiguration:

internal class Program
{
    private static readonly Configuration _configuration = new();

    private static async Task Main(string[] args)
    {
        var host = Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(b => b.Build().Bind(_configuration))
            .ConfigureServices((context, services) =>
            {
                services.AddSingleton(_configuration);
            })
            .Build();

        await host.RunAsync();
    }
}


Ideally, I would like to redefine content.Configuration so that its type matches Configuration (my custom class), in order to directly get values without hardcoding, for example: context.Configuration.Token. But I understand that this may not be possible.
Was this page helpful?