asp.net core 2.1 配置管理
1. 直接读取配置
startup类中使用 configuration["connectionstring"], configuration["aliyunaksk:ak"]
如果在service中想读取配置, 就先注入iconfiguration configuration
2. 配置强类型化读取
现有配置节点如下
"osssettings": {
"configitems": [
{
"name": "ali_",
"domain": "img.",
"officaldomain": "img.",
"accessid": "",
"accesskey": "",
"endpoint": ",
"bucketname": "",
"platform": "ali"
}
],
"currentossname": "al",
"templateossname": ""
}定义一个接口, 并实现这个接口.
public interface iosssettings
{
ienumerable<ossconfig> configitems { get; }
string currentossname { get; }
string templateossname { get; }
}然后在startup的configureservices中添加注入
services.addsingleton<iosssettings>((os) =>
{
var section = configuration.getsection("osssettings");
return section.get<osssettings>();
});之后就可以在任何地方愉快滴使用 iosssettings来注入使用了
3. 外置配置文件
public class program { public static void main(string[] args) { createwebhostbuilder(args).build().run(); } private static iconfiguration configuration { get { var configuration = new configurationbuilder() .setbasepath(directory.getcurrentdirectory()) .addjsonfile("appsettings.json", optional: false, reloadonchange: true) // custom config file .addjsonfile("globalsettings.json", optional: false, reloadonchange: false) .build(); return configuration; } } public static iwebhostbuilder createwebhostbuilder(string[] args) => webhost.createdefaultbuilder(args) .useconfiguration(configuration) .usestartup<startup>(); }
新建一个类globalsettings
services.configure<globalsettings>(configuration);
需要使用options注入使用, 见 https://www.cnblogs.com/qinzb/p/9297143.html
然后就可以使用上面介绍的方式来注入使用了