配置框架
配置以key-value的字符串键值对的方式存在,使用时只用关心key-value就可以了
支持从不同的数据源读取配置,例如:内存,命令行,环境变量,文件等
核心组件包
- Microsoft.Extensions.Configuration
- Microsoft.Extensions.Configuration.Abstractions
Demo
- 从内存读取配置
- 从命令行读取配置
- 从环境变量读取配置
- 从文件中获取配置
- 代码监听配置变更
- 把配置绑定到已有对象上
从内存读取配置
- IConfiguration
- ConfigurationBuilder 核心
- IConfigurationRoot 获取配置的根
- IConfigurationSection 读分层键
实例
代码
internal class Program
{
static void Main(string[] args)
{
IConfigurationBuilder builder = new ConfigurationBuilder();
//注入内存数据源
builder.AddInMemoryCollection(new Dictionary<string,string>() {
{
"key1","value1" },
{
"key2","value2" },
{
"seckey1:key3","value13" },
{
"seckey2:key4","value24" },
{
"seckey2:key5:key1","value251" },
});
//获取配置的根IConfigurationRoot
IConfigurationRoot root = builder.Build();
Console.WriteLine(root["key1"]);
Console.WriteLine(root["key2"]);
//使用IConfigurationSection读取分层键
IConfigurationSection section = root.GetSection("seckey1");
Console.WriteLine($"seckey1:key3:{
section["key3"]}");
Console.WriteLine($"seckey1:key4:{
section["key4"]}");//读不到,没值
IConfigurationSection section2 = root.GetSection("seckey2");
Console.WriteLine($"seckey2:key4:{
section2["key4"]}");
var section3 = section2.GetSection("key5");
Console.WriteLine($"seckey2:key5:key1:{
section3["key1"]}");
}
}
输出结果:
value1
value2
seckey1:key3:value13
seckey1:key4:
seckey2:key4:value24
seckey2:key5:key1:value251
IConfigurationRoot 是继承IConfiguration,也可以使用IConfiguration
IConfiguration configuration = root;
IConfigurationSection section2 = configuration.GetSection("seckey2");
Console.WriteLine($"seckey2:key4:{
section2["key4"]}");
var section3 = section2.GetSection("key5");
Console.WriteLine($"seckey2:key5:key1:{
section3["key1"]}");
从命令行读取配置
配置Key-Value格式:
- 普通 key-value
- 双横杠前缀 --key=value 或–key value,等号与空格不能混用
- 正斜杠 /key=value 或 /key value,等号与空格不能混用
- 可以用单横杠定义key的别名
组件包
在基础的两个包后还要引用多一个命令行的包Microsoft.Extensions.Configuration.CommandLine