1.8 配置框架:让服务无缝适应各种环境.pdf

    1. static void Main(string[] args)
    2. {
    3. IConfigurationBuilder builder = new ConfigurationBuilder();
    4. // 注入内存配置源
    5. builder.AddInMemoryCollection(new Dictionary<string, string>()
    6. {
    7. { "key1","value1" },
    8. { "key2","value2" },
    9. // 使用 : 作为 section 分隔符
    10. { "section1:key4","value4" },
    11. { "section2:key5","value5" },
    12. { "section2:key6","value6" },
    13. { "section2:section3:key7","value7" }
    14. });
    15. // 构建配置,并将其付给配置根
    16. IConfigurationRoot configurationRoot = builder.Build();
    17. ///IConfiguration config = configurationRoot;
    18. Console.WriteLine(configurationRoot["key1"]);
    19. Console.WriteLine(configurationRoot["key2"]);
    20. IConfigurationSection section = configurationRoot.GetSection("section1");
    21. Console.WriteLine($"key4:{section["key4"]}");
    22. Console.WriteLine($"key5:{section["key5"]}");
    23. IConfigurationSection section2 = configurationRoot.GetSection("section2");
    24. Console.WriteLine($"key5_v2:{section2["key5"]}");
    25. var section3 = section2.GetSection("section3");
    26. Console.WriteLine($"key7:{section3["key7"]}");
    27. }

    image.png