dotnet appsettings reload

following demo shows how appsettings properties can be reloaded

the important thing here is that settings them selves are not something critical

the question is what to do with all singletones that may depend on them and even worthe those registered dynamicaly

using System.Text.Json;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;

var builder = WebApplication.CreateBuilder(args);

// i'm here only for demo purposes to create separate file, it might be something like instead
File.WriteAllText("demo.json", JsonSerializer.Serialize(new { demo = new Demo { Number = 42 } }));

// add one more configuration file side by side with appsettings.json
builder.Configuration.AddJsonFile("demo.json", optional: true, reloadOnChange: true);

// how we are usualy registering settings
builder.Services.AddSingleton<Demo>(p => p.GetRequiredService<IConfiguration>().GetSection(nameof(Demo)).Get<Demo>());

// alternative approach, it can live side by side with previous one, it does not registers `Demo` but instead adds IOptions, IOptionsSnapshot and IOptionsMonitor

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

// how we are usualy working with configs
// i wont be refreshed
app.MapGet("/singleton", ([FromServices]Demo demo) => demo);
// curl localhost:5000/singleton
// {"number":42}

// alternative approach with IOptions
// technicaly works same way as previous and wont be refreshed
app.MapGet("/options", ([FromServices]IOptions<Demo> demo) => demo.Value);
// curl localhost:5000/options
// {"number":42}

// alternative approach with IOptionsSnapshot
// i will be refreshed, BUT i will add some perf because computing on each request
app.MapGet("/snapshot", ([FromServices]IOptionsSnapshot<Demo> demo) => demo.Value);
// curl localhost:5000/snapshot
// {"number":42}

// alternative approach with IOptionsSnapshot
// i will be refreshed
app.MapGet("/monitor", ([FromServices]IOptionsMonitor<Demo> demo) => demo.CurrentValue);
// curl localhost:5000/monitor
// {"number":42}



curl -s localhost:5000/singleton | jq
curl -s localhost:5000/options | jq
curl -s localhost:5000/snapshot | jq
curl -s localhost:5000/monitor | jq

echo -n '{"demo":{"Number":5}}' > demo.json

# last two will be updated

public class Demo {
    public int Number { get; set; }

after running this program we can check that all endpoints return expected response

and then change settings file and see what and how endpoints responses will be changed

all this was done on top of options documentation