配置系统

microsoft.extensions.configuration
microsoft.extensions.configuration.json
microsoft.extensions.configuration.binder
microsoft.extensions.options.configurationextensions

  1. 监控配置源
  2. 多种配置源且有优先级
  3. 统一的查找配置项语法
  4. 依赖注入

读取JSON格式的配置文件

{
  "persons": [
    {
      "id": 100,
      "info": {
        "name": "msy",
        "age": 18,
        "skills": [ "CSharp", "Java", "Python" ]
      }
    },
    {
      "id": 101,
      "info": {
        "name": "wxb",
        "age": 19,
        "skills": [ "Javascript", "sql", "ruby" ]
      }
    },
    {
      "id": 102,
      "info": {
        "name": "zwj",
        "age": 20,
        "skills": [ "Go", "Php", "Rust" ]
      }
    }
  ]
}

读取简单类型

IConfigurationBuilder configBuilder = new ConfigurationBuilder();
// optional=true 找不到配置文件抛出异常  reloadOnChange=true 配置文件被修改,内存也跟着变,false,配置文件被修改,内存不变
configBuilder.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
IConfigurationRoot configRoot = configBuilder.Build();

/* 读取简单类型,如数字,字符串,GUID,DateTime,这种方式读取的类型都是字符串,需要自己进行类型转换。
 */
// 查询第1个人员的名字和年龄
Console.WriteLine(configRoot["persons:0:info:name"]);
Console.WriteLine(int.Parse(configRoot.GetRequiredSection("persons:0:info")["age"]));
Console.WriteLine(configRoot.GetSection("persons:0:info:name").Value);
Console.WriteLine(configRoot.GetRequiredSection("persons:0:info").GetValue<int>("age"));
// 查询所有的人员掌握的技能
IEnumerable<IConfigurationSection> sections = configRoot.GetSection("persons").GetChildren();
foreach (IConfigurationSection section in sections)
{
    IEnumerable<IConfigurationSection> skills = section.GetSection("info:skills").GetChildren();
    foreach (IConfigurationSection skill in skills)
    {
        Console.WriteLine(skill.Value);
        Console.WriteLine(skill.Path);
        Console.WriteLine(skill.Key);
    }
}

映射成类

/* 读取复杂类型,映射到类
 */
// 查询第1个人员的名字和年龄
ObjectPersonModel model = configRoot.GetSection("persons:0:info").Get<ObjectPersonModel>(options => options.ErrorOnUnknownConfiguration = true);
Console.WriteLine(model.name);
Console.WriteLine(model.age);
Console.WriteLine(string.Join(",", model.skills));
var ret = configRoot.GetSection("persons").Get<IList<RelationalPersonModel>>();
Console.WriteLine(ret[0].id);

结合依赖注入的配置

IOptionsSnapshot适合aspnetcore

posted @ 2022-08-04 00:50  数字游民  阅读(86)  评论(0编辑  收藏  举报