Reputation: 1340
I had a problem setting up configuration for an ASP.NET Core 5 website, and my searches came up short of a solution.
Failing code first...
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonFile(...
.AddEnvironmentVariables();
IConfiguration configuration = configurationBuilder.Build();
var host = Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(config => {
config.AddConfiguration(configuration);
})
.ConfigureLogging(builder => {
builder.AddConfiguration(configuration);
})
.ConfigureWebHostDefaults(webBuilder => {
webBuilder
.UseConfiguration(configuration)
.UseStartup<Startup>();
});
return host;
}
Startup.cs
public class Startup
{
private readonly IConfiguration _configuration;
public Startup(IConfiguration configuration)
{
_configuration = configuration; // <-- configuration was missing settings
}
...
The problem was this: in startup, configuration
was coming in without the settings that I had provided via files, secrets, etc.
I have intentionally left (in the above code) all of the dead ends I tried. (And lo, they were many...)
My posted solution, however, shows what I actually needed to do.
Upvotes: 0
Views: 730
Reputation: 1340
The key to having all my config show up in Startup turned out to be the call (as seen below) to webBuilder.ConfigureAppConfiguration
from within the call to ConfigureWebHostDefaults
in Program.cs
public static IHostBuilder CreateHostBuilder(string[] args)
{
var configurationBuilder = new ConfigurationBuilder()
.AddJsonFile(...
.AddEnvironmentVariables();
IConfiguration configuration = configurationBuilder.Build();
var host = Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder => {
webBuilder
.ConfigureAppConfiguration(config => {
config.AddConfiguration(configuration);
})
.UseStartup<Startup>();
});
return host;
}
Maybe this is obvious to others, but it certainly wasn't obvious to me.
PS - I see that in .NET 6 there will be a new approach as outlined here. I mention that because this whole exercise of building my own configuration in advance is because I need configuration info in order to configure the website build itself. As described in the above-referenced article, this chicken-egg problem has been addressed in .NET 6.
Upvotes: 1