配置系统-读取配置4
读取其他配置(非本地文件):
一.从命令行读取
新建控制台项目:
添加Nuget引用:
Install-Package Microsoft.Extensions.Options
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.Binder
install-package Microsoft.Extensions.Configuration.CommandLine
-- Demo.cs
using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace A_ReadCommandLine { internal class Demo { private readonly IOptionsSnapshotoptions; public Demo(IOptionsSnapshot options) { this.options = options; } public void GetStudentInfo() { Console.WriteLine(options.Value.ToString()); } public void GetClassInfo() { Console.WriteLine(options.Value.classInfo.ToString()); } } }
--program.cs
using A_ReadCommandLine; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; ServiceCollection sc = new ServiceCollection(); sc.AddScoped(); ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddCommandLine(args); IConfigurationRoot configurationRoot = configurationBuilder.Build(); sc.AddOptions().Configure (s => configurationRoot.Bind(s))// 添加配置绑定 .Configure (c => configurationRoot.GetSection("ClassInfo").Bind(c)); //绑定班级信息 using (ServiceProvider sp = sc.BuildServiceProvider()) { Demo d = sp.GetRequiredService (); d.GetStudentInfo(); } public class Student { public string Name { get; set; } public int Age { get; set; } public ClassInfo classInfo { get; set; } public override string ToString() { return $"我是{Name},今年{Age}岁"; } } public class ClassInfo { public string Teacher { get; set; } public string ClassName { get; set; } public int[] Seat { get; set; } public override string ToString() { return $"老师是{Teacher} 班级:{ClassName} 坐在第{Seat[0]}排第{Seat[1]}列"; } }
生成项目,找到Bin下面的EXE文件
通过控制台输出
回车执行:
命令行操作太麻烦? VS项目属性可以直接配置:
再运行试试:
如何获取班级信息(嵌套类型) 扁平化处理:
修改program.cs
using (ServiceProvider sp = sc.BuildServiceProvider()) { Demo d = sp.GetRequiredService(); d.GetStudentInfo(); d.GetClassInfo();//增加打印班级信息 }
打开项目属性:
添加: name=张三 age=12 classInfo:teacher=李四 classInfo:className=一年级 classInfo:seat:0=2 classInfo:seat:1=3
执行看效果:
二.从环境变量读取
使用上面的代码:
1.添加Nuget包
Install-Package Microsoft.Extensions.Configuration.EnvironmentVariables
2.修改Program.cs
3.修改电脑环境变量/通过VS修改
或者通过VS进行修改:环境变量不建议随便修改
环境变量: age=12,classInfo:className=一年级,classInfo:seat:0=2 ,classInfo:seat:1=3,classInfo:teacher=李四,name=张三
再来运行看结果:
配置变量最后自定义前缀:用来区分不同的应用,也可以避免与电脑的系统变量冲突:
//configurationBuilder.AddEnvironmentVariables();//改为下面 // 默认只获取STU_开头的环境变量 configurationBuilder.AddEnvironmentVariables("STM_");//STM学生管理系统使用
然后需要在环境变量的参数前面都增加STM_
环境变量: STM_age=12,STM_classInfo:className=一年级,STM_classInfo:seat:0=2 ,STM_classInfo:seat:1=3,STM_classInfo:teacher=李四,STM_name=张三
运行结果:
还有更多的配置读取Xml/Ini..