08 | 配置框架:让服务无缝适应各种环境
核心组件包
- Microsoft.Extensions.Configuration.Abstractions
- Microsoft.Extensions.Configuration
在NuGet添加
配置框架
- 以
**key-value**
字符串键值对的方式抽象了配置 - 支持从不同的数据源读取配置
- 命令行、环境变量、文件
配置框架核心类型
- IConfiguration
- IConfigurationRoot
- 表示我们的配置的根
- IConfigurationSection
- Section作用是指,当我们的配置不是简单的key-value的shi'hou,比如把配置分组
- IConfigruationBuilder
- 构建配置的核心,我们所有的设置都是在build中完成
配置框架扩展点
注入我们自己的配置源,也就是说我们可以指定任意的配置的数据来源
- IConfigurationSource
- IConfigurationProvider
示例
新建控制台应用程序
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
namespace ConfigurationDemo
{
class Program
{
static void Main(string[] args)
{
// 使用默认的ConfigurationBuilder的实现
IConfigurationBuilder builder = new ConfigurationBuilder();
// 注入一个内存的配置数据源,键值对形式
builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "key1","value1"},
{ "key2","value2"}
});
// 使用Build把所有的配置构建出来,并且获得一个configurationRoot
// configurationRoot就表示我们的配置的根,也就是说我们读取配置的动作
// 都是需要从IConfigurationRoot这个对象读取的
IConfigurationRoot configurationRoot = builder.Build();
// 读取key1和key2
Console.WriteLine(configurationRoot["key1"]);
Console.WriteLine(configurationRoot["key2"]);
}
}
}
使用默认的ConfigurationBuilder
获取IConfigurationBuilder
的实例
将一个字典集合注入一个内存配置源
使用IConfigurationBuilder.Build()
将配置构建出来,获取IConfigurationRoot
对象
根据IConfigurationRoot
获取配置内容
当我们的程序不仅仅是简单的key-value的时候,例如分组
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
namespace ConfigurationDemo
{
class Program
{
static void Main(string[] args)
{
// 使用默认的ConfigurationBuilder的实现
IConfigurationBuilder builder = new ConfigurationBuilder();
// 注入一个内存的配置数据源,键值对形式
builder.AddInMemoryCollection(new Dictionary<string, string>
{
{ "key1","value1"},
{ "key2","value2"},
// section每一节使用冒号来作为节的分隔符的
{ "section1:key1","section2.value1"},
{ "section2:key1","section2.value1"},
{ "section2:key2","section2.value2"}
});
// 使用Build把所有的配置构建出来,并且获得一个configurationRoot
// configurationRoot就表示我们的配置的根,也就是说我们读取配置的动作
// 都是需要从IConfigurationRoot这个对象读取的
IConfigurationRoot configurationRoot = builder.Build();
// 读取key1和key2
//Console.WriteLine(configurationRoot["key1"]);
//Console.WriteLine(configurationRoot["key2"]);
// 获取一个section
IConfigurationSection configurationSection = configurationRoot.GetSection("section2");
Console.WriteLine(configurationSection["key1"]);
Console.WriteLine(configurationSection["key2"]);
}
}
}
section
每一节使用冒号来作为节的分隔符的
通过IConfigurationRoot.GetSection()
获取一个Section
使用IConfigurationSection
获取配置内容
也可以使用套娃来实现多节分组
在字典集合中添加:{ "section2:section3:key1","section2.section3.value1"}
使用configurationRoot.GetSection("section2").GetSection("section3");
获取
本文作者:hiwwwk
本文链接:https://www.cnblogs.com/wwwk/p/15873351.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
分类:
标签:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步