首先咱们使用.NET Core的配置框架须要安装额外的NuGet扩展包,下面是列举最经常使用的几个扩展包以及所对应的配置功能json
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的构造,代码以下:c#
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(); }
输出结果:app
Job:Student Name:Foo Sex:Male
那么咱们能够看到一个configuration的构建的步骤:框架
定义ConfigurationBuilderui
为ConfigurationBuilder添加ConfigurationSourcethis
经过ConfigurationBuilder的Build方法完成构建命令行
首先咱们在项目的调试的应用程序参数加入命令行参数:3d
代码修改以下:调试
builder.AddInMemoryCollection(new Dictionary<string, string>() { {"Name","Foo"}, {"Sex","Male" }, {"Job","Student" }, }) .AddCommandLine(args);
输出:code
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"]}"; }
效果以下:
咱们会发现,以前的环境变量都被过滤了,只能读取被过滤前缀后的环境变量
配置环境变量时的注意点:
首先咱们新建一个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; }
效果以下:
以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; }
效果以下: