.NET Core 为我们提供了一套用于配置的 API,它为程序提供了运行时从文件、命令行参数、环境变量等读取配置的方法。配置都是键值对的形式,并且支持嵌套,.NET Core 还内建了从配置反序列化为 POCO 对象的支持。
目前支持以下配置 Provider:
如果现有 Provider 不能满足你的使用场景,还允许自定义 Provider,比如从数据库中读取。
包管理器中搜索 "Microsoft.Extensions.Configuration",所有与配置相关的包都会列举出来
从包的名称基本就可以看出它的用途,比如
是 Json 配置的 Provider,
- Microsoft.Extensions.Configuration.Json
是命令行参数配置的 Provider,还有. NET Core 程序中使用 User Secrets 存储敏感数据这篇文章中使用的
- Microsoft.Extensions.Configuration.CommandLine
。
- Microsoft.Extensions.Configuration.UserSecrets
Json 配置,需要安装
包。
- Microsoft.Extensions.Configuration.Json
命令行下安装执行以下命令
- dotnetadd package Microsoft.Extensions.Configuration.Json -v 1.1.2
调用 AddJsonFile 把 Json 配置的 Provider 添加到 ConfigurationBuilder 中。
- class Program
- {
- public static IConfigurationRoot Configuration { get; set; }
- static void Main(string[] args)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("appsettings.json");
- Configuration = builder.Build();
- }
- }
如果使用Xml 或 Ini,只需安装相应的包,然后调用相应的扩展方法 AddXmlFile("appsettings.xml) 或 AddIniFile("appsettings.ini")。
SetBasePath 是指定从哪个目录开始查找 appsettings.json。如果 appsettings.json 在configs 目录中,那么调用 AddJsonFile 应该指定的路径为 "configs/appsettings.json"。
下面是演示用的 Json 配置,后面会讲解所有读取它的方法
- {
- "AppId": "12345",
- "Logging": {
- "IncludeScopes": false,
- "LogLevel": {
- "Default": "Debug",
- "System": "Information",
- "Microsoft": "Information"
- }
- },
- "GrantTypes": [
- {
- "Name": "authorization_code"
- },
- {
- "Name": "password"
- },
- {
- "Name": "client_credentials"
- }
- ]
- }
1. 使用 Key 读取
- Configuration["AppId"]; // 结果 12345
- Configuration["Logging:IncludeScopes"]; // 结果 false
- Configuration["Logging:LogLevel:Default"]; // 结果 Debug
- Configuration["GrantTypes:0:Name"]; // 结果 authorization_code
读取嵌套的配置,使用冒号隔开;读取数组形式的配置,使用数组的下标索引,0 表示第一个。
如在其他地方用到 Configuration 的时候,可以通过构造函数注入 IConfiguration。
首先配置 IConfiguration 的依赖
- services.AddSingleton<IConfiguration>(Configuration);
然后在通过构造函数注入
- private readonly IConfiguration _configuration;
- public GetConfig(IConfiguration configuration)
- {
- _configuration = configuration;
- }
2. 使用
这是一个扩展方法,使用它需要安装
- GetValue<T>
包。
- Microsoft.Extensions.Configuration.Binder
- Configuration.GetValue < int > ("AppId", 12345); // 结果 12345
- Configuration.GetValue < bool > ("Logging:IncludeScopes", false); // 结果 false
- Configuration.GetValue < string > ("Logging:LogLevel:Default", "Debug"); // 结果 Debug
- Configuration.GetValue < string > ("GrantTypes:0:Name", "authorize_code"); // 结果 authorization_code
GetValue 方法的泛型形式有两个重载,一个是 GetValue
3. 使用
这种方式需要安装
- Options
包。
- Microsoft.Extensions.Options.ConfigurationExtensions
调用 AddOptions() 添加使用 Options 需要的服务。
- services.AddOptions()
定义与配置对应的 POCO 类
- public class MyOptions {
- public int AppId {
- get;
- set;
- }
- public LoggingOptions Logging {
- get;
- set;
- }
- public List < GrantType > GrantTypes {
- get;
- set;
- }
- public class GrantType {
- public string Name {
- get;
- set;
- }
- }
- }
- public class LoggingOptions {
- public bool IncludeScopes {
- get;
- set;
- }
- public LogLevelOptions LogLevel {
- get;
- set;
- }
- }
- public class LogLevelOptions {
- public string Default {
- get;
- set;
- }
- public string System {
- get;
- set;
- }
- public string Microsoft {
- get;
- set;
- }
- }
绑定整个配置到 POCO 对象上
- services.Configure<MyOptions>(Configuration);
也可以绑定特定节点的配置
- services.Configure<LoggingOptions>(Configuration.GetSection("Logging"));
或
- services.Configure<LogLevelOptions>(Configuration.GetSection("Logging:LogLevel"));
在需要用到配置的地方,通过构造函数注入,或者直接使用 ServiceProvider 获取。
- private readonly MyOptions _myOptions;
- public GetConfig(IOptions<MyOptions> myOptionsAccessor)
- {
- _myOptions = myOptionsAccessor.Value;
- }
或
- var myOptionsAccessor = serviceProvider.GetService<IOptions<MyOptions>>();
- var myOptions = myOptionsAccessor.Value;
4. 使用
- Get<T>
是. NET Core 1.1 才引入的。
- Get<T>
- var myOptions = Configuration.Get<MyOptions>();
或
- var loggingOptions = Configuration.GetSection("Logging").Get<LoggingOptions>();
5. 使用
和
- Bind
类似,建议使用
- Get<T>
。
- Get<T>
- var myOptions = new MyOptions();
- Configuration.Bind(myOptions);
或
- var loggingOptions = new LoggingOptions();
- Configuration.GetSection("Logging").Bind(loggingOptions);
支持配置文件变化自动重新加载配置。使用
- IOptionsSnapshot
也很简单,AddJsonFile 有个重载,指定 reloadOnChange:true 即可。
- IOptionsSnapshot
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("configs/appsettings.json", optional: false, reloadOnChange: true);
内存中配置调用AddInMemoryCollection(),其余和 Json 配置一样。
- var dict = new Dictionary < string,
- string > {
- {
- "AppId",
- "12345"
- }, {
- "Logging:IncludeScopes", "false"
- }, {
- "Logging:LogLevel:Default", "Debug"
- }, {
- "Logging:LogLevel:System", "Information"
- }, {
- "Logging:LogLevel:Microsoft", "Information"
- }, {
- "GrantTypes:0:Name", "authorization_code"
- }, {
- "GrantTypes:1:Name", "password"
- }, {
- "GrantTypes:2:Name", "client_credentials"
- }
- };
- var builder = new ConfigurationBuilder().AddInMemoryCollection(dict);
或
- var builder = new ConfigurationBuilder()
- .AddInMemoryCollection();
- Configuration["AppId"] = "12345";
命令行参数配置需要安装
包。
- Microsoft.Extensions.Configuration.CommandLine
调用 AddCommandLine() 扩展方法将命令行配置 Provider 添加到 ConfigurationBuilder 中。
- var builder = new ConfigurationBuilder()
- .AddCommandLine(args);
传递参数有两种形式
- dotnetrun /AppId=12345
或
- dotnetrun --AppId 12345
如果为 --AppId 提供一个缩写的参数 - a,那么执行
会报在 switch mappings 中没有 - a 定义的错误。
- dotnet run -a 12345
幸好 AddCommandLine 还有一个重载,可以传一个 switch mapping。
- var builder = new ConfigurationBuilder().AddCommandLine(args, new Dictionary < string, string > {
- {
- "-a",
- "AppId"
- }
- });
这样再运行下面的命令就不会报错了。
- dotnetrun -a 12345
环境变量配置需要安装
包。
- Microsoft.Extensions.Configuration.EnvironmentVariables
调用 AddEnvironmentVariables() 扩展方法将环境变量配置 Provider 添加到 ConfigurationBuilder 中。
- var builder = new ConfigurationBuilder()
- .AddEnvironmentVariables();
获取所有的环境变量
- Environment.GetEnvironmentVariables();
根据名称获取环境变量
- Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
自定义配置 Provider 需要继承 IConfigurationSource 实现自己的配置源,以及继承 ConfigurationProvider,重写 Load 方法。
关于自定义配置 Provider,我写了两个开源包,Cxlt.Extensions.Configuration.EF 和 Cxlt.Extensions.Configuration.Yaml,通过这两个项目,我会详细讲解如何实现自己的配置 Provider。文章《实现自己的. NET Core 配置 Provider 之 EF》和《实现自己的. NET Core 配置 Provider 之 Yaml》过几天也会发布。
.NET Core 的配置 API 允许同时使用多个配置 Provider。
- var builder = new ConfigurationBuilder()
- .SetBasePath(Directory.GetCurrentDirectory())
- .AddJsonFile("configs/appsettings.json")
- .AddXmlFile("configs/appsettings.xml")
- .AddCommandLine(args)
- .AddEnvironmentVariables();
如果两个 Provider 都有相同的配置,那么添加 Provider 的顺序就非常重要了,因为后加入的会覆盖前面的。
另外建议环境变量的配置 Provider 放到最后。
.NET Core 的配置是很基础的内容,学起来自然不难,基本上动手实践一遍就能掌握。越是简单的东西,在日后的开发中可能帮你节约很多时间。希望这篇文章对你有帮助,请点赞支持一下,也欢迎关注 "chengxulvtu" 公众号,提前获取新文章。
来源: http://www.cnblogs.com/nianming/p/7083964.html