aspnet / Hosting

[Archived] Code for hosting and starting up an ASP.NET Core application. Project moved to https://github.com/aspnet/Extensions and https://github.com/aspnet/AspNetCore
Apache License 2.0
552 stars 312 forks source link

UseConfiguration doesn't respect reloadOnChange #1532

Closed lonix1 closed 6 years ago

lonix1 commented 6 years ago

I want to start logging before webhost, so startup errors are logged. So I followed Serilog's recommended init order: 1) configuration, 2) logging, 3) webhost. I'm not using CreateDefaultBuilder().

So my Program.cs has:

// setup config
var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var configuration = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("appsettings.json", optional:false, reloadOnChange:true)
  .AddJsonFile($"appsettings.{envName}.json", optional:true, reloadOnChange:true)
  .AddEnvironmentVariables()
  .AddCommandLine(args)
  .Build();

// setup Serilog logging
Log.Logger = new LoggerConfiguration()
  .ReadFrom.Configuration(configuration)            // <<< uses config from above
  .CreateLogger()

// setup webhost
new WebHostBuilder()
  .UseConfiguration(configuration)                  // <<< uses config from above
  .UseKestrel()
  .UseContentRoot(Directory.GetCurrentDirectory())
  .UseStartup<Startup>()
  .UseSerilog()
  .Build()
  .Run();

This works, but changes in appsettings.json are not detected even though I specified reloadOnChange:true.

However when I use ConfigureAppConfiguration() then changes are detected:

new WebHostBuilder()
  .ConfigureAppConfiguration((context, config) => {
    // .. duplicate config here
  })
  .UseKestrel()
  .UseContentRoot(Directory.GetCurrentDirectory())
  .UseStartup<Startup>()
  .UseSerilog()
  .Build()
  .Run();

But that means duplication and possibly unforseen problems.

There are various issues around this, but without being an expert in the underlying framework, they don't address my problem. Can this be solved, is it a bug, by design, or am I doing it wrong?

EDIT The docs change often so I didn't see this which implies that I should use ConfigureAppConfiguration(). However the problem remains - how do I do this neatly without duplicating code?

Tratcher commented 6 years ago

Likely duplicate of https://github.com/aspnet/Hosting/issues/1430

Rather than duplicating your config builder in ConfigureAppConfiguration, you could chain in the config you've already built with config.UseConfiguration(configuration). That should honor reload better than WebHostBuilder.UseConfiguration.

lonix1 commented 6 years ago

@Tratcher That did it! Like mentioned in the issue you linked, some of the docs are confusing, but I'm glad you mentioned this will be reworked in 3.x.

For anyone who needs this, the exact solution is:

.ConfigureAppConfiguration((context, config) => {
  config.AddConfiguration(configuration);
})