.NET6新东西--ConfigurationManager

简介: .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的源代码中就可以看出来:

/// <summary>
    /// Configuration is mutable configuration object. It is both an <see cref="IConfigurationBuilder"/> and an <see cref="IConfigurationRoot"/>.
    /// As sources are added, it updates its current view of configuration. Once Build is called, configuration is frozen.
    /// </summary>
    public sealed class ConfigurationManager : IConfigurationBuilder, IConfigurationRoot, IDisposable
    {
        private readonly ConfigurationSources _sources;
        private readonly ConfigurationBuilderProperties _properties;
        private readonly object _providerLock = new();
        private readonly List<IConfigurationProvider> _providers = new();
        private readonly List<IDisposable> _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的时候才去创建。这里建议根据实际项目情况使用。


目录
相关文章
|
3月前
|
SQL XML Java
.Net视频总结
.Net视频总结
60 0
|
3月前
.NET - Scrutor
该文档介绍了Scrutor库的安装和使用。在命令行中,可以使用`NuGet\Install-Package Scrutor -Version 4.2.1`来安装。Scrutor提供了两个扩展方法给`ServiceCollection`:`Scan`和`Decorate`。`Scan`用于从指定程序集中扫描并批量注册符合规则(如以&quot;Service&quot;结尾的类)的服务,注册类型为其实现的接口,并设置为Scoped生命周期。`Decorate`则用于装饰已注册的服务。
|
11月前
net't'y
net't'y
58 0
.NET6新东西--CallerArgumentExpression
.NET6新东西--CallerArgumentExpression
185 0
.NET6新东西--CallerArgumentExpression
.NET 6新东西--PeriodicTimer
.NET 6新东西--PeriodicTimer
173 0
|
SQL 人工智能 前端开发
|
编解码 Linux 内存技术