ASP.NET Core

介绍

可使用多种类型数据源(json、内存、xml、ini、command、env...),还可以自定义配置源;
支持多环境版本、如果多次添加相同的配置,后添加的会覆盖之前添加的;
热加载,修改配置文件后可不重启项目,重新将文件加载到内存;
Configuraion相关的Package都是以Microsoft.Extensions.Configuration开头的,支持多种配置方式;

核心对象

IConfiguration:存储配置数据
IConfigurationBuilder:构造IConfiguration对象
IConfigurationProvider:向IConfiguration提供数据,IConfiguration内部包含IConfigurationProvider对象
IConfigurationSource:加载配置文件,例如:json、xml

自定义数据源

ConfigurationSource:

public class PropertiesConfigurationSource : IConfigurationSource
        {
            public string Path { get; set; }
            public PropertiesConfigurationSource(string path)
            {
                this.Path = path;
            }
            public IConfigurationProvider Build(IConfigurationBuilder builder)
            {
                return new PropertiesConfigurationProvider(this.Path);
            }
        }

ConfigurationProvider:

        public class PropertiesConfigurationProvider : ConfigurationProvider
        {
            public string Path { get; set; }
            public PropertiesConfigurationProvider(string path)
            {
                this.Path = path;
            }

            public override void Load()
            {
                Dictionary<string, string> dict = new Dictionary<string, string>();
                string[] lines = File.ReadAllLines(this.Path);
                string[] pair = null;
                foreach (var line in lines)
                {
                    if (!string.IsNullOrWhiteSpace(line))
                    {
                        pair = line.Split('=');
                        if (pair.Length == 2)
                        {
                            dict.TryAdd(pair[0], pair[1]);
                        }
                    }
                }
                this.Data = dict;
            }
        }

扩展方法:

        public static class ConfigurationBuilderExtension
        {
            public static IConfigurationBuilder AddPropetiesFile(this IConfigurationBuilder configurationBuilder, string path)
            {
                configurationBuilder.Add(new PropertiesConfigurationSource(path));
                return configurationBuilder;
            }
        }

添加数据源

asp.net core框架中创建了ConfigurationBuilder,且添加了appsettings.json,不需要我们手动添加这个文件,所以应使用已存在的ConfiguraionBuilder添加数据源,使用下面的方式添加数据源

Host.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{
      config.AddJsonFile("connectionStrings.json", false, true);//添加JSON配置源
      config.Add(new MemoryConfigurationSource { InitialData = new Dictionary<string, string>{}});//添加内存配置源
      config.AddEnvironmentVariables("T_");//添加环境变量
      config.AddXmlFile("appsetting.xml");//添加XML数据源
      config.AddCommandLine(args);//添加命令行数据源
}); 

读取配置:

弱类型读取

Configuration["Logging:Default:t1"]        //按层级取值,返回值是字符串类型

Configuration.GetSection("Ips").Value    //返回值是字符串类型

强类型读取

string[] ips = Configuration.GetSection("Ips").Get<string[]>();//将Ips节点转为数组

LogLevel logLevel = Configuration.GetSection("Logging:LogLevel").Get<LogLevel>();//节点转为对象

int CACHE_TIME = configuration.GetValue<int>("CACHE_TIME", 20);//20是默认值,需要安装 Microsoft.Extensions.Configuration.Binder包

//强类型绑定
Logging logging = new Logging();
Configuration.GetSection("Logging").Bind(logging);//将Logging节点绑定到Logging对象

选项模式(Options)

可以认为这是一种强类型的形式,使用Configure()添加配置,IOptions的默认实现是OptionsManager

// 使用配置文件来注册实例
services.Configure<MyOptions>(Configuration.GetSection("Sign"));
// 指定具体名称
services.Configure<MyOptions>("my", Configuration.GetSection("Sign"));
// 配置所有实例?
services.ConfigureAll<MyOptions>(Configuration.GetSection("Sign"));

//使用Lambda添加配置:
services.Configure<MyOptions>(o => o.DefaultValue = true);
services.Configure<MyOptions>("my", o => o.DefaultValue = true);
services.ConfigureAll<MyOptions>(o => o.DefaultValue = true);

IOptions:它会一直缓存选项对象,可以理解为单例选项对象
IOptionsSnapshot:每个请求都重读配置以获得新的选项对象(支持热更新)
IOptionsMonitor:一直缓存选项对象,但当配置源发生更改时自动更新我的选项对象时使用(支持热更新,并缓存,推荐)
IOptionsMonitor,更强大的Options,它的用法和IOptionsSnapshot没有区别,不同的时,它多了一个配置文件发生改变之后事件处理

案例1:遍历数组节点

{"Configs": [
      {
        "Name": "db1",
        "DBType": "sqlserver",
        "ConnectionString": "Server=192.168.0.44,1433;initial catalog=FMS;uid=sa;pwd=123;Pooling=true;Max Pool Size=40000;Min Pool Size=0;MultipleActiveResultSets=true;",
        "RepositoryName": ""
      }
    ]
}

//--------------------------------------
private void LoadConfigs(IConfiguration configuration)
        {
            var configs = configuration.GetSection("Configs");var configCount = configs.GetChildren().Count();
            for (int i = 0; i < configCount; i++)
            {
                var config = configs.GetSection(i.ToString());
                this.DBConfigs.Add(new DBConfigInfo()
                {
                    Name = config.GetValue<string>("Name"),
                    DBType = config.GetValue<string>("DBType"),
                    ConnectionString = config.GetValue<string>("ConnectionString")
                });
            }
        }
        public List<DBConfigInfo> DBConfigs { get; private set; }
    }

参考:
https://www.cnblogs.com/artech/p/inside-asp-net-core-05-09.html

原文地址:https://www.cnblogs.com/fanfan-90/p/14111155.html