.NET Core的配置系统特点:
多数据源、多环境版本、热加载、修改配置文件不重启项目
添加配置源
添加JSON、XML文件作为配置元之前需要设置基础路径, SetBasePath(Environment.CurrentDirectory)
在已存在的ConfigurationBuilder中添加数据源, WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((hostingContext, config) =>{//...在此处添加数据源...});
添加JSON配置源
public static IWebHostBuilder CreateWebHostBuilder(string[] args)
{
return WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(configurationBuilder => configurationBuilder.AddJsonFile("hosts.json", false, true))
.UseStartup<Startup>();
}
添加内存配置源
Dictionary<string, string> source = new Dictionary<string, string>
{
["longDatePattern"] = "dddd, MMMM d, yyyy",
["longTimePattern"] = "h:mm:ss tt",
["shortDatePattern"] = "M/d/yyyy",
["shortTimePattern"] = "h:mm tt"
};
IConfiguration config = new ConfigurationBuilder()
.Add(new MemoryConfigurationSource { InitialData = source })
.Build();
添加环境变量数据源
IConfiguration config = new ConfigurationBuilder().AddEnvironmentVariables()
添加XML数据源
IConfiguration config = new ConfigurationBuilder().AddXmlFile("appsetting.xml")
读取配置:
在程序中可以注入IConfigurationRoot来读取配置,但是建议注入强类型Options,这样只需要注入对应的Options,而不是获取整个配置
弱类型读取:
1、Configuration["Logging:Default:t1"] //按层级取值,返回值是字符串类型
2、Configuration.GetSection("Ips").Value //字符串
强类型读取:
1、string[] ips = Configuration.GetSection("Ips").Get<string[]>();
2、LogLevel logLevel = Configuration.GetSection("Logging:LogLevel").Get<LogLevel>();
3、Logging logging = new Logging();
Configuration.GetSection("Logging").Bind(logging);//强类型绑定
4、CACHE_TIME = configuration.GetValue<int>("CACHE_TIME", 20);//20是默认值
5、services.Configure<Logging>(Configuration.GetSection("Logging"));//将对象注册到容器,在构造函数中获取POCO对象,称为Options模式
Options:
使用Configure()添加配置,IOptions的默认实现是OptionsManager
通过配置文件添加配置:
// 使用配置文件来注册实例
services.Configure<MyOptions>(Configuration.GetSection("Sign"));
// 指定具体名称
services.Configure<MyOptions>("my", Configuration.GetSection("Sign"));
// 配置所有实例
services.ConfigureAll<MyOptions>(Configuration.GetSection("Sign"));
使用Lambda添加配置:
// 最简单的注册方式
services.Configure<MyOptions>(o => o.DefaultValue = true);
// 指定具体名称
services.Configure<MyOptions>("my", o => o.DefaultValue = true);
// 配置所有实例
services.ConfigureAll<MyOptions>(o => o.DefaultValue = true);
接收参数:
public HomeController(IOptions<LogLevelClass> logLevelOption) { }
未完待续...