12 | monitor configuration changes: hot update the core configuration capabilities
This section explains how to use code to monitor configuration changes and make some moves
When we need to track configuration changes occur, you can perform certain operations when changes occur
The main configuration provides a GetReloadToken method, which is a key method for tracking configuration
Then use the code on a
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true);
var configurationRoot = builder.Build();
IChangeToken token = configurationRoot.GetReloadToken();
IChangeToken has two properties and a method
public interface IChangeToken
{
bool HasChanged { get; }
bool ActiveChangeCallbacks { get; }
IDisposable RegisterChangeCallback(Action<object> callback, object state);
}
Then Callback Registration
token.RegisterChangeCallback(state =>
{
Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
}, configurationRoot);
Start the program, modify the configuration file, triggering Callback
Repeatedly modify the configuration file has no effect?
After IChangeToken because this object can only be used once, that is to capture and execute the code change, we need to re-acquire a new IChangeToken, re-registration
token.RegisterChangeCallback(state =>
{
Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
token = configurationRoot.GetReloadToken();
token.RegisterChangeCallback(state2 =>
{
Console.WriteLine();
}, configurationRoot);
}, configurationRoot);
This will turn into an infinite loop process, Microsoft actually provides a quick extension method is more convenient to use, this method can help us easily handle this matter, which means that after each trigger can complete rebind
ChangeToken.OnChange(() => configurationRoot.GetReloadToken(), () =>
{
Console.WriteLine($"Key1:{configurationRoot["Key1"]}");
Console.WriteLine($"Key2:{configurationRoot["Key2"]}");
Console.WriteLine($"Key3:{configurationRoot["Key3"]}");
});
The first argument is a method of obtaining IChangeToken
The second parameter is a process of changing the implantation method
Start the program, modify the configuration file, multiple trigger Callback
This work is Creative Commons Attribution - NonCommercial - ShareAlike 4.0 International License Agreement for licensing.
Welcome to reprint, use, repost, but be sure to keep the article signed by Zheng Ziming (containing links: http://www.cnblogs.com/MingsonZheng/), shall not be used for commercial purposes, be sure to publish the same work based on the paper license modification .
If you have any questions, please contact me ([email protected]).