当前位置:网站首页>ASP.NET CORE配置选项(下篇)
ASP.NET CORE配置选项(下篇)
2022-04-23 05:55:00 【begeneral】
本篇文章使用的配置项对应POCO对象:
public class Profile
{
public Gender Gender { get; set; }
public int Age { get; set; }
public ContactInfo ContactInfo { get; set; }
}
public class ContactInfo
{
public string EmailAddress { get; set; }
public string PhoneNo { get; set; }
}
1、IOptionsSnapshot
在上一篇文章中我们介绍了IOptions和IOptionsMonitor,这里我们讲一下IOptionsSnapshot。我们看一下下面这个配置文件:
{
"foo": {
"gender": "Male",
"age": "18",
"contactinfo": {
"emailAddress": "foobar.outlook.com",
"phoneno": "123"
}
},
"bar": {
"gender": "Female",
"age": "20",
"contactinfo": {
"emailAddress": "foobar.outlook.com",
"phoneno": "456"
}
}
}
这里有2个配置,配置项的字段是一样的,但是每个配置都有自己的名称:foo和bar。这就像是一个班级里面有很多学生,每个学生都拥有自己的属性(姓名、年龄等)。
这种配置的使用方式和上篇文章介绍了那两种其实区别不大,下面看一下代码:
这是在startup的ConfigureServices函数中的代码:
var configuration1 = new ConfigurationBuilder().AddJsonFile(path: "profile1.json", optional: false, reloadOnChange: true).Build();
services.AddOptions().Configure<Profile>("foo", configuration1.GetSection("foo"));
services.AddOptions().Configure<Profile>("bar", configuration1.GetSection("bar"));
这是获取配置的代码:
var fooProfile = _snapOptions.Get("foo");
var barProfile = _snapOptions.Get("bar");
_snapOptions是定义的全局变量:IOptionsSnapshot<Profile> _snapOptions,通过依赖注入给它赋值。
这种方式其实是给配置取了一个名字,然后通过名字去获取配置。
2、MemoryConfigurationSource
前面我们都是用配置文件,因为这是最常见一种配置方式,下面我们看一下使用内存来配置。
var memorySource = new Dictionary<string, string>
{
["gender"] = "Male",
["age"] = "20",
["ContactInfo:emailaddress"] = "[email protected]",
["ContactInfo:phoneno"] = "123"
};
var memeoryConfig = new ConfigurationBuilder().AddInMemoryCollection(memorySource).Build();
services.AddOptions().Configure<Profile>(memeoryConfig);
gender和age是Profile类的属性,所以直接赋值即可。但是后面两个是ContactInfo类的属性,所以需要把ContactInfo放到前面,然后用冒号引用这个类的属性。这里注意一定是冒号,而不是逗号。
获取配置的方式和前面一样,这里就不再赘述了。
版权声明
本文为[begeneral]所创,转载请带上原文链接,感谢
https://blog.csdn.net/niechaoya/article/details/115814049
边栏推荐
- Makefile foundation, common functions and general makefile
- Node访问服务器端静态资源
- Vs can be compiled, but there will be a red underline to indicate the problem of undefined identifiers
- 几款笔记软件的优缺点
- POJ-The Unique MST
- Incremental update of client software
- JS高频面试题
- ECMAScript历史
- Error in created hook: “ReferenceError: “Promise”未定义“
- 【ES6】 Promise相关(事件循环,宏/微任务,promise,await/await)
猜你喜欢
随机推荐
ARM常用汇编指令
Node访问服务器端静态资源
ES6
Notes on advanced points of C language 5
Node data flow
PN结、二极管原理详解与应用
Running QT program in visual Stdio
五个路由守卫的使用
查漏补缺(一)
HDU-Memory Control
Arm common assembly instructions
时间戳转格式化日期
服务器常见错误代码 总结
查漏补缺(七)
Header内置对象
Palindromic Primes
Node数据流
Use of C language and
FOC SVPWM函数PWMC_SetPhaseVoltage解析
赛氪-zeal









