栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

.NET6新东西--ConfigurationManager

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

.NET6新东西--ConfigurationManager

.NET6于2021年11月9日凌晨0点30分与VS2022一同发布,从今天开始我将带领大家来看一下.NET6新引入的内容。今天我们先来看一下.NET6中的ConfigurationManager。
这里所说的ConfigurationManager并不是.NET Framework中的静态类ConfigurationManager,而是.NET6为Minimal API引入的一个新内容,它位于Microsoft.Extensions.Configuration中。简单的说.NET6中的ConfigurationManager就是.NET Framework 中 ConfigurationBuilder和ConfigurationRoot的结合体,我们在ConfigurationManager的源代码中就可以看出来:

/// 
    /// Configuration is mutable configuration object. It is both an  and an .
    /// As sources are added, it updates its current view of configuration. Once Build is called, configuration is frozen.
    /// 
    public sealed class ConfigurationManager : IConfigurationBuilder, IConfigurationRoot, IDisposable
    {
        private readonly ConfigurationSources _sources;
        private readonly ConfigurationBuilderProperties _properties;

        private readonly object _providerLock = new();
        private readonly List _providers = new();
        private readonly List _changeTokenRegistrations = new();
        private ConfigurationReloadToken _changeToken = new();
    	//more code
    	//....
    	 // Don't rebuild and reload all providers in the common case when a source is simply added to the IList.
        private void AddSource(IConfigurationSource source)
        {
            lock (_providerLock)
            {
                var provider = source.Build(this);
                _providers.Add(provider);

                provider.Load();
                _changeTokenRegistrations.Add(ChangeToken.OnChange(() => provider.GetReloadToken(), () => RaiseChanged()));
            }

            RaiseChanged();
        }
            //more code
            //.....
    }

从上面的源码中我们可以看出来ConfigurationManager在添加IConfigurationSource的时候会注册IConfigurationProvider。每添加一个新的配置源时都会去创建一个IConfigurationProvider,并去加载配置数据和注册配置更新事件。因此才能在添加了source之后拿到Configuration中的配置。
就目前来说,ConfigurationManager主要用在Minimal API中,但是我们也可以在其他类型的项目中直接使用。而且.NET6为我们做了兼容,即使在.NET6中使用原来的IConfigurationBuilder也没有问题。但是这里有个问题,虽说使用ConfigurationManager会更加简单(对于编写代码来说),不用像以前那样先声明一个IConfigurationBuilder对象,并注册好后再创建一个IConfiguration对象,但性能会差一些,注册的配置源越多就越明显。因为每次ConfigurationManager注册配置源都会区创建并注册IConfigurationProvider,但以前的方式则是在最后Build的时候才去创建。这里建议根据实际项目情况使用。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/904719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号