0

I have a series of .NET Core worker services (targeting .NET 6). I am accessing configuration data from appsettings.json through hostcontext and that works fine:

public static async Task Main(string[] args)
{
    // Start the application
    await CreateHostBuilder(args).Build().RunAsync();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
        .UseWindowsService()
        .ConfigureServices((hostContext, services) =>
        {
            // I can access config data like this:
            var connectionString = hostcontext.Configuration["ConnectionStrings:MyConnectionString"];
        });

However, I now need to get configuration data from within Main() before CreateHostBuilder() is called.

I can do something like this, but is there a better way? It feels wrong to build a ConfigurationBuilder just to grab this one value, is there a more efficient way to do this?

public static async Task Main(string[] args)
{
    // Get the configuration
    var environmentName = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT") ?? "Production";

    var builder = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appsettings.json")
        .AddJsonFile($"appsettings.{environmentName}.json", true, true);

    var configuration = builder.Build();

    // Start the application
    await CreateHostBuilder(args).Build().RunAsync();
}
3
  • 1
    Why do you need it early? Can you use a background service or singleton instead? Commented Feb 14, 2023 at 19:23
  • It's for a logger configuration...I am switching my Serilog to log to a SQL DB in addition to the flat files it currently generates, and I wanted the cxn string to be pulled from the config. Because I'm logging any exceptions on app start, I have to grab that cxn string before the app starts... PS: Your articles on async have taught me so much! I truly appreciate all of the effort you've spent educating people like me! :) Commented Feb 15, 2023 at 5:59
  • 1
    Using a separate config builder is the best way I know of. Commented Feb 15, 2023 at 11:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.