当前位置:网站首页>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
边栏推荐
猜你喜欢
随机推荐
Detailed explanation and application principle of token
查漏补缺(三)
赛氪-zeal
The difference between single quotation mark, double quotation mark and back quotation mark in shell script
Use of shell scripts & and 𞓜
Assembly base code example
Router对象、Route对象、声明式导航、编程式导航
VHDL finite state machine (FSM) code example
QT add qserialport class to realize serial port operation
MOS管特性和导通过程
2020 Jiangsu Collegiate Programming Contest-A.Array
Use of C language and
VHDL-任意分频器(50%占空比)
Set与Map
oninput 一个函数达到控制多个oninput的效果(将本输入框的内容作为参数)【很实用,很实用】
千呼万唤始出来
Node模版引擎(ejs, art-template)
useCenterHook
FOC SVPWM函数PWMC_SetPhaseVoltage解析
Node data flow