Json File - Changed Tracking and Reload

2019-08-24 02:04发布

问题:

I have a .NET Core 2.0 console application which has a AppConfiguration file which provides different app-settings. I have added in the main-method the creation of a ConfigurationBuilder object and added the reloadOnChange flag for that JSON file like in the code below.

static void Main(string[] args)
{
    Console.WriteLine("Program started...");
    Console.WriteLine("Stop Program by Ctrl+C");

    //Add Exit Possibility
    Console.CancelKeyPress += CurrentDomain_ProcessExit;

    //Add Configuration Builder
    Console.Write("Load Shared Configuration...");
    Configuration = new ConfigurationBuilder()
        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
        .AddJsonFile("SharedAppConfiguration.json", optional: false, reloadOnChange: true)
        .Build();
    Console.WriteLine("done");

}

How can I catch or get information about the event, that the JSON file "SharedAppConfiguration.json" has changed?

I've tried to do something like this:

Configuration.GetSection("AppConfiguration").Bind(appConfiguration);

But like it looks, there is no .Bind method in .NET Core console application - in ASP.NET it’s available.

回答1:

In order to use the Bind method on the configuration objects, you also need the Microsoft.Extensions.Configuration.Binder package. Microsoft.Extensions.Configuration only comes with the base stuff to work with the configuration, and Microsoft.Extensions.Configuration.Json is only the loader for JSON files.

To answer your other question, about how to get notified about configuration changes for JSON configuration files with reloadOnChange: true, you can use the reload change token for this. It’s easiest to use the ChangeToken.OnChange helper function for that:

var configuration = new ConfigurationBuilder()
    .AddJsonFile("file.json", optional: false, reloadOnChange: true)
    .Build();

// register change callback
ChangeToken.OnChange(() => configuration.GetReloadToken(), () => {
    Console.WriteLine("Configuration changed");
});

If you are using the options pattern, you can also use the options monitor for this.



标签: c# .net-core