Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid static value in ASP.NET Core Program.cs

In my CreateWebHostBuilder() method I've added the AWS Systems Manager Parameter Store as an additional source for Configuration Builder:

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        return WebHost.CreateDefaultBuilder(args)
                  .ConfigureAppConfiguration(builder =>
                  {
                      builder.AddSystemsManager("/ConfigureStoreName/");
                  })
                  .UseStartup<Startup>();
    }
}

Instead of hardcoding "/ConfigureStoreName/" I'd like to make this a configuration value.

When I call .ConfigureAppConfiguration() do I have access to the config values from appsettings.json that .CreateDefaultBuilder() uses? If so how would I update my code to call it? If not what is the best approach to avoid using a static value in the CreateWebHostBuilder() method?

like image 444
Josh Avatar asked Mar 31 '26 22:03

Josh


1 Answers

Pre load setting file with that information.

If for example the setting file contained

{
  //...

  "AWS": {
    "Profile": "local-test-profile",
    "Region": "us-west-2",
    "ConfigureSource": {
      "Path": "/ConfigureStoreName/"
    }
  }

  //...
}

load that up in a configuration to extract the value.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) {

    var configuration = new ConfigurationBuilder()
        .AddJsonFile("appsettings.json") //<-- or whichever file has that information
        .Build();

    string path = configuration.GetValue<string>("AWS:ConfigureSource:Path");
    //Or a strongly typed model with aws options

    return WebHost.CreateDefaultBuilder(args)
              .ConfigureAppConfiguration(builder =>
              {
                  builder.AddSystemsManager(path);
              })
              .UseStartup<Startup>();
}
like image 79
Nkosi Avatar answered Apr 02 '26 12:04

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!