一.配置框架的核心类库

首先我们使用.NET Core的配置框架需要安装额外的NuGet扩展包,下面是列举最常用的几个扩展包以及所对应的配置功能

NuGet Package Description
Microsoft.Extensions.Configuration 配置框架的核心库,提供有关Configuration的抽象类和实现类
Microsoft.Extensions.Configuration.CommandLine 能够使用命令参数进行配置
Microsoft.Extensions.Configuration.EnvironmentVariables 能够使用环境变量进行配置
Microsoft.Extensions.Configuration.Json 能够使用json文件进行配置
Microsoft.Extensions.Configuration.Xml 能够使用xml文件进行配置
Microsoft.Extensions.Configuration.Ini 能够使用Ini文件进行配置
Microsoft.Extensions.Configuration.Binder 支持强类型对象绑定配置

二.一个Configuration的构建

下面我们在控制台使用内存存储配置信息并且完成一个Configuration的构造,代码如下:

 static void Main(string[] args)
{
//定义一个ConfigurationBuilder
IConfigurationBuilder builder = new ConfigurationBuilder(); //添加ConfigurationSource
builder.AddInMemoryCollection(new Dictionary<string, string>()
{
{"Name","Foo"},
{"Sex","Male" },
{"Job","Student" },
}); //通过Build构建出IConfiguration
IConfiguration configuration = builder.Build(); foreach (var item in configuration.GetChildren())
{
Console.WriteLine($"{item.Key}:{item.Value}");
}
Console.ReadLine();
}

输出结果:

Job:Student
Name:Foo
Sex:Male

那么我们可以看到一个configuration的构建的步骤:

  • 定义ConfigurationBuilder

  • 为ConfigurationBuilder添加ConfigurationSource

  • 通过ConfigurationBuilder的Build方法完成构建

三.通过命令行配置

首先我们在项目的调试的应用程序参数加入命令行参数:

代码修改如下:

 builder.AddInMemoryCollection(new Dictionary<string, string>()
{
{"Name","Foo"},
{"Sex","Male" },
{"Job","Student" },
})
.AddCommandLine(args);

输出:

Age:23
Job:Student
Name:Ryzen
Sex:Male

同时我们在输出结果看到,key为Name的value变化了,证明当不同配置源存在相同Key时,会被后添加的配置源覆盖其value

四.通过环境变量配置

下面的环节由于出于演示效果,通过WPF程序来演示,首先创建好一个wpf项目,界面如下:

我们在项目的调试的环境变量添加几个参数:

在App.cs中构建一个静态属性IConfiguration,代码如下:

    public partial class App : Application
{
public static IConfiguration MyConfigration => new ConfigurationBuilder()
.AddEnvironmentVariables() }

MainWindow.cs:

    public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void Button_Click(object sender, RoutedEventArgs e)
{
LoadEnv(); } private void LoadEnv()
{
string envString = string.Empty;
this.textbox_env.Text = $"Env__IsProduction:{App.MyConfigration.GetSection("Env")["IsProduction"]}"+"\n";
this.textbox_env.Text += $"Env__IsDevelopment:{App.MyConfigration.GetSection("Env")["IsDevelopment"] }"+"\n";
this.textbox_env.Text += $"Class__Team__Group:{App.MyConfigration.GetSection("Class:Team")["Group"]}";
}
}

实现效果:

在注入环境变量时,还支持去前缀过滤筛选注入,修改App.cs:

    public partial class App : Application
{
public static IConfiguration MyConfigration => new ConfigurationBuilder()
.AddEnvironmentVariables("Env:") }

修改MainWindow.cs:

        private void LoadEnv()
{
string envString = string.Empty;
this.textbox_env.Text = $"Env__IsProduction:{App.MyConfigration.GetSection("Env")["IsProduction"]}"+"\n";
this.textbox_env.Text += $"Env__IsDevelopment:{App.MyConfigration.GetSection("Env")["IsDevelopment"] }"+"\n";
this.textbox_env.Text += $"Class__Team__Group:{App.MyConfigration.GetSection("Class:Team")["Group"]}" +"\n";
//过滤前缀后
this.textbox_env.Text += $"IsProduction:{App.MyConfigration["IsProduction"]}";
}

效果如下:

我们会发现,之前的环境变量都被过滤了,只能读取被过滤前缀后的环境变量

配置环境变量时的注意点:

  • 和json等文件不同,环境变量的Key是以__双下划线为分层键,而不是:冒号
  • 分层读取的时候是以冒号:来进行读取

五.通过文件来配置

1.创建和读取配置文件

首先我们新建一个Configurations文件夹,然后再该文件夹创建三个配置文件

appsetting.json:

{
"Human": {
"Name": "Foo",
"Body": {
"Height": 190,
"Weight": 170
},
"Sex": "Male",
"Age": 24,
"IsStudent": true
}
}

appsetting.xml:

<?xml version="1.0" encoding="utf-8" ?>
<Configuration>
<DbServers>
<SqlSever>12</SqlSever>
<MySql>11</MySql>
</DbServers>
</Configuration>

appsetting.ini:

[Ini]
IniKey1=IniValue1
IniKey2=IniValue2

在App.cs分别注入这三个文件:

    public partial class App : Application
{
public static IConfiguration MyConfigration => new ConfigurationBuilder()
.AddEnvironmentVariables("Env:")
.AddJsonFile(@"Configurations\appsetting.json", false, true)
.AddXmlFile(@"Configurations\appsetting.xml", false, true)
.AddIniFile(@"Configurations\appsetting.Ini")
.Build(); }

修改MainWindow代码,分别读取这三个文件:

private void Button_Click(object sender, RoutedEventArgs e)
{
LoadEnv();
LoadJson();
LoadXML();
LoadIni();
} private void LoadJson()
{
var jsonString = string.Empty;
foreach (var item in App.MyConfigration.GetSection("Human").GetChildren())
{
if (item.Key.Contains("Body"))
{
foreach (var body in item.GetChildren())
{
jsonString += $"{body.Key}:{body.Value} \n";
}
}
else
{
jsonString += $"{item.Key}:{item.Value} \n";
} }
this.textbox_json.Text = jsonString;
} private void LoadXML()
{
var xmlString = string.Empty;
foreach (var item in App.MyConfigration.GetSection("DbServers").GetChildren())
{
xmlString += $"{item.Key}:{item.Value} \n";
}
this.textbox_xml.Text = xmlString;
} private void LoadIni()
{
var iniString = string.Empty;
foreach (var item in App.MyConfigration.GetSection("Ini").GetChildren())
{
iniString += $"{item.Key}:{item.Value} \n";
}
this.textbox_ini.Text = iniString;
}

效果如下:

2.支持文件变更时重新读取和设置变更监视

以json文件为例,我们在App.cs注入json文件时调用此方法

AddJsonFile(@"Configurations\appsetting.json", false, true)

该方法有是一个重载方法,最常用的是三个参数的重载方法,下面是三个参数的作用

  • path:文件路径

  • optional:默认为false,当找不到该文件路径会报错,true则不报错

  • reloadOnChange:默认为false,当为true时支持配置文件变更后重新读取

首先,我们为appsetting.json文件设置属性,复制到输出目录=>如果较新则复制,生成操作=>内容

然后我们通过一个内置的静态方法监控文件变更,修改MainWindows.cs:

public MainWindow()
{
InitializeComponent();
ChangeToken.OnChange(() => App.MyConfigration.GetReloadToken(), () =>
{
MessageBox.Show("文件发生变更了");
});
}

效果如下:

六.强类型绑定配置

首先我们创建一个类用于绑定配置,代码如下:

    public class MyHumanConfig
{
public string Name { get; set; } public Body Body { get; set; }
public string Sex { get; set; } public int Age { get; set; } public bool IsStudent { get; set; }
} public class Body
{
public int Height { get; set; } public int Weight { get; set; }
}

在Mainwindow.cs新增以下代码:

  private void Button_Click(object sender, RoutedEventArgs e)
{
LoadEnv();
LoadJson();
LoadXML();
LoadIni();
LoadBind();
} private void LoadBind()
{
var bindString = string.Empty;
MyHumanConfig config = new MyHumanConfig();//声明变量 App.MyConfigration.GetSection("Human").Bind(config);//绑定变量 foreach (var configProperty in config.GetType().GetProperties())
{
if (configProperty.PropertyType==typeof(Body))
{
var body = configProperty.GetValue(config) as Body;
foreach (var bodyProperty in body.GetType().GetProperties())
{
bindString += $"{bodyProperty.Name}:{bodyProperty.GetValue(body)} \n";
}
}
else
{
bindString += $"{configProperty.Name}:{configProperty.GetValue(config)} \n";
} }
this.textbox_bind.Text = bindString;
}

效果如下:

.NET Core 3.x之下的配置框架的更多相关文章

  1. ASP.NET Core 1.0 基础之配置

    来源https://docs.asp.net/en/latest/fundamentals/configuration.html ASP.NET Core 1.0支持不同的配置选项.应用配置数据可以是 ...

  2. Linux CentOS7部署ASP.NET Core应用程序,并配置Nginx反向代理服务器

    前言: 本篇文章主要讲解的是如何在Linux CentOS7操作系统搭建.NET Core运行环境并发布ASP.NET Core应用程序,以及配置Nginx反向代理服务器.因为公司的项目一直都是托管在 ...

  3. Asp.Net SignalR 使用记录 技术回炉重造-总纲 动态类型dynamic转换为特定类型T的方案 通过对象方法获取委托_C#反射获取委托_ .net core入门-跨域访问配置

    Asp.Net SignalR 使用记录   工作上遇到一个推送消息的功能的实现.本着面向百度编程的思想.网上百度了一大堆.主要的实现方式是原生的WebSocket,和SignalR,再次写一个关于A ...

  4. IDM主机上安装融合应用程序配置框架

    IDM主机上安装融合应用程序配置框架   安装Oracle融合应用程序>设置>身份和访问管理节点安装融合应用程序配置框架 由于我们使用Oracle VirtualBox虚拟机这一次,我们在 ...

  5. NET Core度身定制的AOP框架

    NET Core度身定制的AOP框架 多年从事框架设计开发使我有了一种强迫症,那就是见不得一个应用里频繁地出现重复的代码.之前经常Review别人的代码,一看到这样的程序,我就会想如何将这些重复的代码 ...

  6. asp.net core 教程(五)-配置

    Asp.Net Core-配置 Asp.Net Core-配置 在这一章,我们将讨论 ASP.NET Core项目的相关的配置.在解决方案资源管理器中,您将看到 Startup.cs 文件.如果你有以 ...

  7. Dora.Interception,为.NET Core度身打造的AOP框架:全新的版本

    Dora.Interception 1.0(Github地址:可以访问GitHub地址:https://github.com/jiangjinnan/Dora)推出有一段时间了,最近花了点时间将它升级 ...

  8. Dora.Interception, 一个为.NET Core度身打造的AOP框架:不一样的Interceptor定义方式

    相较于社区其他主流的AOP框架,Dora.Interception在Interceptor提供了完全不同的编程方式.我们并没有为Interceptor定义一个接口,正是因为不需要实现一个预定义的接口, ...

  9. Dora.Interception, 一个为.NET Core度身打造的AOP框架[3]:Interceptor的注册

    在<不一样的Interceptor>中我们着重介绍了Dora.Interception中最为核心的对象Interceptor,以及定义Interceptor类型的一些约定.由于Interc ...

随机推荐

  1. openfire配置好文

    http://www.th7.cn/db/mysql/201406/59838.shtml 下载地址:Openfire 3.8.2 Release

  2. 熊海CMS_1.0 代码审计

    熊海是一款小型的内容管理系统,1.0版本是多年前的版本了,所以漏洞还是比较多的,而且审计起来难度不大,非常适合入门,所以今天我进行这款cms的代码审计.程序安装后使用seay源代码审计系统打开,首先使 ...

  3. 电脑莫名重启,VS代码丢失的解决办法

    今天写了一天的代码,然后电脑放在公司了,出去看电影(公司组织红色文化培训..)回来发现电脑重启,再打开电脑,VS的代码都不见了.好慌.... 别慌处理办法来了: 打开everything(没有的可以下 ...

  4. SpringBoot开发二十-Redis入门以及Spring整合Redis

    安装 Redis,熟悉 Redis 的命令以及整合Redis,在Spring 中使用Redis. 代码实现 Redis 内置了 16 个库,索引是 0-15 ,默认选择第 0 个 Redis 的常用命 ...

  5. 蓝桥杯-PREV31-小朋友排队

    解法: 这题有点像冒泡排序,但是做这题并不需要冒泡排序. 假设第i个小朋友比第j个小朋友高,而且i < j 为了把队伍排成从小到大,第i个小朋友一定要去第j个小朋友的右边.又因为只能交换位置相邻 ...

  6. 2015-09-15-git配置

    https://help.github.com/articles/set-up-git/ git上传是忽略一些文件 在每个git的项目中有一个.gitignore文件,将忽略的文件或文件夹输入即可. ...

  7. 操作的系统的PV操作

    转自:https://blog.csdn.net/sunlovefly2012/article/details/9396201 在操作系统中,进程之间经常会存在互斥(都需要共享独占性资源时) 和同步( ...

  8. Oauth2.0 协议简介及 php实例代码

    转自:http://www.dahouduan.com/2017/11/21/oauth2-php/ https://blog.csdn.net/halsonhe/article/details/81 ...

  9. HexoC++第04课 构造析构.md

    C++第04课 构造析构.mdhtml {overflow-x: initial !important;}#write, body { height: auto; } #write, #write h ...

  10. mongodb配置windows服务启动

    第一步 下载MongoDB http://www.mongodb.org/downloads 第二步 解压到D:\mongodb\目录下,为了命令行的方便,可以把D:\mongodb\bin加到系统环 ...