537mfb
537mfb

Reputation: 1482

Double call of OnChange callback happening first detection of change by IOptionMonitor

I'm playing around with Dependency Injection and IOptions<T> pattern and found the following oddity that I would like to understand. Hope someone here can explain it.

So I have a .NET 7 WPF application to which I added from Nuget the following packages:

  1. CommunityToolkit.Mvvm version 8.0.0
  2. Microsoft.Extensions.Configuration version 7.0.0
  3. Microsoft.Extensions.Configuration.Json version 7.0.0
  4. Microsoft.Extensions.Options.ConfigurationExtensions version 7.0.0

In App.xaml.cs I configured the options:

var configuration = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
        .Build();
_serviceProvider = new ServiceCollection()
        .Configure<AppSettings>(configuration.GetSection(nameof(AppSettings)))
        .BuildServiceProvider();

My appSettings.json contains a single property:

{
  "AppSettings": {
    "IsUpdating": false
  }
}

And my AppSettings.cs has the proper class definition:

public partial class AppSettings : ObservableObject
{
    [ObservableProperty]
    private bool isUpdating;
}

So in my ViewModel class I inject IOptionsMonitor<AppSettings> and listen to changes:

public partial class ViewModel : ObservableObject
{
    [ObservableProperty]
    private AppSettings settings;

    public ViewModel(IOptionsMonitor<AppSettings> appSettings)
    {
         appSettings.OnChange<AppSettings>(SettingsChanged);
         settings = appSettings.CurrentValue;
    }

    private void SettingsChanged(AppSettings appSettings)
    {
         Settings.IsUpdating = appSettings.Updating;
    }
}

Now I place a breakpoint inside the SettingsChanged method and run the app.

I then open the appSettings.json file and change the value of IsUpdating. The first time I make a change, the breakpoint stops the code twice in a row - any further changes only stops once. If I close the app and start it again this reproduces 100% of the time - first change calls SettingsChanged twice, following changes to the file only calls it once.

So my first question is, what happens when it detects the first change I make that doesn't happen any other time after that until I restart the app?

I've also notice that it calls SettingsChanged even if I just saved the file without any change to it - shouldn't it only call it if a change was detected?

Upvotes: 1

Views: 1111

Answers (0)

Related Questions