Alessandro Ciurlo
Alessandro Ciurlo

Reputation: 122

ASPNET Core: events raised by settings changes using IOptionsMonitor

I have created a basic ASPNET Core Web Application (.NET6.0) with MVC pattern. The goal is to monitor the changes in appsettings.json using events raised by IOptionsMonitor. My appsettings.json is the following

{
  "Example1": {
    "param1": "sample1",
    "param2": "sample2"
  },

  "Example2": {
    "param3": "sample3",
    "param4": "sample4"
  }
}

I have create two POCO class to archive settings values :

public class Example1
  {
      public string param1 { get; set; }
      public string param2 { get; set; }
  }

  public class Example2
  {
     public string param3 { get; set; }
     public string param4 { get; set; }
  }

In the main method of web application I have registered the configuration instances:

 public static void Main(string[] args)
  {
      var builder = WebApplication.CreateBuilder(args);
      .....
      builder.Services.Configure<Example1>(builder.Configuration.GetSection("Example1"));
      builder.Services.Configure<Example2>(builder.Configuration.GetSection("Example2")); 
      ....
  }

Then in the home controller I want to monitor changes to the settings contained in sections example1 and example2. So I've injected IOptionsMonitor for Example1 and Example2 and I've subscribes the onchanges events in this way

 public class HomeController : Controller
 {
     private IDisposable _example1listener;
     private IDisposable _example2listener;

     public HomeController( IOptionsMonitor<Example1> example1, IOptionsMonitor<Example2> example2)
     {
         _example1listener = example1.OnChange(ChangeExample1Listener);
         _example2listener = example2.OnChange(ChangeExample2Listener);
     }

     private void ChangeExample1Listener(Example1 example)
     {
         Console.Write("Changed Example 1");
     }

     private void ChangeExample2Listener(Example2 example)
     {
         Console.Write("Changed Example 2");
     }

     ~HomeController()
     {
         _example1listener?.Dispose();
         _example2listener?.Dispose();
     }
}

When my web application is up and when I edit a value in section Example1 in appsettings.json I expect to myself that ChangeExample1Listener is called. In the same way when I change a value in in section Example2 I expect to myself that ChangeExample2Listener is called according to what I have understood reading the Microsoft documentation

https://learn.microsoft.com/

but what happens is this: whatever setting I change both listener are called. so this is my output

"Changed Example 1" "Changed Example 2"

Is this the expected behavior I'm doing something wrong? in the first case there is a way to know if a setting in a given section is really changed?

Upvotes: 1

Views: 559

Answers (0)

Related Questions