Reputation: 110
We are binding a section of our appsettings.json to an IOptionsMonitor to watch for changes and hot reload. Unfortunately I don't see a way to detect invalid datatype changes. If there is an appsetting that maps to an int, say "IntSetting" : 20
and change it to a decimal, "IntSetting": 20.50
the monitor doesn't appear to detect a change at all.
Code as follows.
Program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseWindowsService()
.ConfigureServices((hostContext, services) =>
{
services.Configure<DaemonConfiguration>(hostContext.Configuration.GetSection("DaemonConfiguration"));
services.AddHostedService<Worker>();
})
.UseNLog();
Worker.cs
public Worker(ILogger<Worker> logger, IOptionsMonitor<DaemonConfiguration> appConfig, IConfiguration configuration)
{
Logger = logger;
Configuration = configuration;
StartDaemonConfigurationProvider(appConfig.CurrentValue);
appConfig.OnChangeDelayed(DaemonConfigurationListener);
}
appConfig.OnChangeDelayed(DaemonConfigurationListener);
is an implementation based on https://github.com/dotnet/aspnetcore/issues/2542#issuecomment-354685749 where we delay registering changes by a second or two so multiple saves can be aggregated. It still points to IOptionsMonitor<T>.OnChange()
eventually with the callback of DaemonConfigurationListener.
The DaemonConfigurationListener function just says "Hey Appsettings changed, run it through our validation function and apply changes". That all works beautifully. The problem is if we make a change that would cause a C# invalid datatype error on startup, I don't see a way to listen for or capture that using the IOptionsMonitor. It never makes it as far as the OnChange() function. It seems that reading of the file is happening earlier on and likely returning and swallowing that error before I get a chance to see it myself.
This is probably a "Feature" to keep the application from trying to do something that would cause it to crash, but I'm curious if there's a way to capture and handle this case myself. We want to protect our users from doing bad things, or at least be able to notify them via logs that they did something bad and it will be ignored. Currently there's no indication that anything happened and no change was made.
Upvotes: 1
Views: 236