The automatic update principle of IOptionsSnapshot & lt; & gt; In dotnetcore, core3.1.1snapshot

Source: Internet
Author: User

The automatic update principle of IOptionsSnapshot in dotnetcore, core3.1.1snapshot
1. First, let's talk about the ChangeToken. OnChange method:

The principle is to register a consumer delegate for a CancellationToken. When CancellationToken Cancel is called, all the delegate code in the CancellationToken will be called for implementation as follows:

public static IDisposable OnChange(Func<IChangeToken> changeTokenProducer, Action changeTokenConsumer){    if (changeTokenProducer == null)    {        throw new ArgumentNullException("changeTokenProducer");    }    if (changeTokenConsumer == null)    {        throw new ArgumentNullException("changeTokenConsumer");    }    Action<object> callback = null;    callback = delegate(object s)    {        IChangeToken changeToken = changeTokenProducer();        try        {            changeTokenConsumer();        }        finally        {            changeToken.RegisterChangeCallback(callback, null);        }    };    return changeTokenProducer().RegisterChangeCallback(callback, null);}

 

2. IOptions <> If the lifecycle is Singleton, the configuration is saved to the Cache during initialization and will not be updated. 3. IOptionsSnapshot <> If the lifecycle is Scope, it will be written to the Cache during initialization, the content is provided by OptionsMonitor. When OptionsMonitor is initialized, the system registers an overloaded configuration method code for ChangeToken of all IOtionsChangeTokenSource <T> objects as follows:
using (IEnumerator<IOptionsChangeTokenSource<TOptions>> enumerator =  this._sources.GetEnumerator()){    while (enumerator.MoveNext())    {        IOptionsChangeTokenSource<TOptions> source = enumerator.Current;        ChangeToken.OnChange(() => source.GetChangeToken(), delegate        {            this.InvokeChanged();        });    }}

Here, the Token in source. GetChangeToken is obtained from IConfigurationRoot. The following code proves that:

public class ConfigurationChangeTokenSource<TOptions> : IOptionsChangeTokenSource<TOptions>    {        private IConfiguration _config;        /// <summary>        /// Constructor taking the IConfiguration instance to watch.        /// </summary>        /// <param name="config">The configuration instance.</param>        public ConfigurationChangeTokenSource(IConfiguration config)        {            if (config == null)            {                throw new ArgumentNullException("config");            }            this._config = config;        }        /// <summary>        /// Returns the reloadToken from IConfiguration.        /// </summary>        /// <returns></returns>        public IChangeToken GetChangeToken()        {            return this._config.GetReloadToken();        }    }

Here _ config is to call AddOptions. config (...) and the ConfigurationRoot registers its own ChangeToken Reload event to the ChangeToken of all IConfigurationProvider objects during initialization. The Code is as follows:

Public ConfigurationRoot (IList <IConfigurationProvider> providers) {if (providers = null) {throw new ArgumentNullException ("providers");} this. _ providers = providers; using (IEnumerator <IConfigurationProvider> enumerator = providers. getEnumerator () {while (enumerator. moveNext () {IConfigurationProvider p = enumerator. current; p. load (); ChangeToken. onChange () => p. getReloadToken (), delegate {this. raiseChanged () ;}}} private void RaiseChanged () {// execute its own _ changeToken OnReload event and reinitialize A ConfigurationReloadToken Interlocked. exchange <ConfigurationReloadToken> (ref this. _ changeToken, new ConfigurationReloadToken ()). onReload ();}

This ensures that the ChangeToken in IConfigurationRoot will also have a Reload event when all configurationproviders Reload. When our configuration changes, our ConfigurationProvider needs to update Data first and then trigger its Reload event to trigger the Reload event of IConfigurationRoot, when OptionsMonitor is initialized, it registers an Update Configuration cache event for ChangeToken of IConfigurationRoot (as mentioned earlier). Therefore, OptionsMonitor updates the configuration cache, then, the new IOptionsSnapshot <> interface object created in the next request can read the updated configuration information.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.