Reloading appsettings.json Without Restarting the Application

Download full source code.

I was chatting with a friend about reloading configuration within a .NET application. He was manually running a background worker that read from appsettings.json every few minutes. He was unaware that .NET has built-in support for reloading configuration without restarting the application.

Here is a simple example of how to do it with a Web API application, but the same principle applies to any .NET application.

First, here is the appsettings.json with the section named “WebApiSettings” -

{
 "WebApiSettings": {
 "StringSetting1": "Hello World!",
 "IntSetting2": 100,
 "BoolSetting3": true
 }
}

Now I need a matching C# class to hold the settings -

1public class WebApiSettings
2{
3 public string? StringSetting1 { get; set; }
4 public int IntSetting2 { get; set; }
5 public bool BoolSetting3 { get; set; }
6}

And it’s all brought together in the Program.cs file -

 1using Microsoft.Extensions.Options;
 2
 3var builder = WebApplication.CreateBuilder(args);
 4
 5builder.Configuration.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
 6
 7builder.Services.Configure<WebApiSettings>(builder.Configuration.GetSection("WebApiSettings"));
 8
 9var app = builder.Build();
10
11app.MapGet("/", (IOptionsMonitor<WebApiSettings> optionsMonitor) => $@"Current settings -
12
13StringSetting1: {optionsMonitor.CurrentValue.StringSetting1} 
14IntSetting2: {optionsMonitor.CurrentValue.IntSetting2} 
15BoolSetting3: {optionsMonitor.CurrentValue.BoolSetting3} 
16
17Change the settings in appsettings.json, save the file, and reload this page.");
18
19app.Run();

Run the application, open the browser to localhost:5000, and you will see the current settings. Change the values in appsettings.json, save the file, and reload the page in the browser. The new values will be displayed without restarting the application.

That’s it!

Download full source code.

comments powered by Disqus

Related