.net core 简单配置框架运用 电脑版发表于:2020/6/18 14:59 ![.netcore](https://img.tnblog.net/arcimg/hb/c857299a86d84ee7b26d181a31e58234.jpg ".netcore") >#Configuration 配置框架:让服务无缝适应各种环境 [TOC] <br/> 核心组件包 ------------ <br/> - Microsoft.Extensions.Configuration.Abstractions - Microsoft.Extensions.Configuration <br/> 配置框架 ------------ <br/> - 以 key-value 字符串键值对的方式抽象了配置 - 支持从各种不同的数据源读取配置(比如:命令行读取,从环境变量读取,从文件读取) <br/> 配置框架核心类型 ------------ <br/> - IConfiguration - IConfigurationRoot (表示配置的根系|完成读取配置的操作实例) - IConfigurationSection (当我们不仅仅是通过key-value获取配置的时候使用,通过冒号(:)做分割) - IConfigurationBuilder (构建我们配置的核心) <br/> 配置框架扩展点 ------------ <br/> - IConfigurationSource - IConfigurationProvider <br/> 简单运用 ------------ <br/> >###项目结构 ![项目结构](https://img.tnblog.net/arcimg/hb/993c4cf93bcc4703863ac19232c53370.png "项目结构") >###通过键值对获取 <br/> >示例代码 ```csharp IConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(new Dictionary<string, string>() { { "key1","value1" }, { "key2","value2" }, { "section1:key4","value3" } }); IConfigurationRoot configurationRoot = builder.Build(); //IConfiguration config = configurationRoot; Console.WriteLine(configurationRoot["key1"]); Console.WriteLine(configurationRoot["key2"]); ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/b812f8a10e9b495e9512b776519cd2b1.png "结果") >###通过 IConfigurationSection 获取分组数据 <br/> >添加代码 ```csharp IConfigurationSection section = configurationRoot.GetSection("section1"); Console.WriteLine($"key4:{section["key4"]}"); Console.WriteLine($"key5:{section["key5"]}"); ``` >结果 ![结果](https://img.tnblog.net/arcimg/hb/388936fbab8f453190020ec81470a166.png "结果") >###通过 IConfigurationSection 获取多重分组数据 <br/> >修改代码 ```csharp IConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddInMemoryCollection(new Dictionary<string, string>() { { "key1","value1" }, { "key2","value2" }, { "section1:key4","value3" }, { "section2:key5","value5" }, { "section2:key6","value6" }, { "section2:section3:key7","value7" }, }); IConfigurationRoot configurationRoot = builder.Build(); //IConfiguration config = configurationRoot; Console.WriteLine(configurationRoot["key1"]); Console.WriteLine(configurationRoot["key2"]); IConfigurationSection section = configurationRoot.GetSection("section1"); Console.WriteLine($"key4:{section["key4"]}"); Console.WriteLine($"key5:{section["key5"]}"); IConfigurationSection section2 = configurationRoot.GetSection("section2"); Console.WriteLine($"key6:{section2["key6"]}"); var section3 = section2.GetSection("section3"); Console.WriteLine($"key7:{section3["key7"]}"); ``` >运行结果 ![运行结果](https://img.tnblog.net/arcimg/hb/4fe52b42b40241eda066ca717a7a96e3.png "运行结果")