当前位置:网站首页>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
边栏推荐
猜你喜欢
微信小程序之点击取消,返回上页,修改上页的参数值,let pages=getCurrentPages() let prevPage=pages[pages.length - 2] // 上一页的数据
Principle and characteristic analysis of triode
Running QT program in visual Stdio
若依框架从零开始
Makefile基础、常用函数及通用Makefile
todesk远程控制软件的使用
常用sql语句收藏
锚点定位——如何设置锚点居页面顶部距离,锚点定位并距离顶部一定偏移
HDU-Tunnel Warfare
SiteServer CMS5.0使用总结
随机推荐
2020 Jiangsu Collegiate Programming Contest-A.Array
Running QT program in visual Stdio
Shell脚本的通配符和特殊符号
Assembly base code example
锚点定位——如何设置锚点居页面顶部距离,锚点定位并距离顶部一定偏移
Generate shortcut
Introduction and application of WMI Technology
C language code specification
HDU-Tunnel Warfare
Joseph sequence segment tree o (nlogn)
HDU-Tunnel Warfare
MOS tube characteristics and conduction process
ASP.NET CORE 配置选项(上篇)
Log writing method (with time)
Redux概述
Incremental update of client software
颜色字符串转换
Detailed explanation and application of PN junction and diode principle
Collection of practical tips for C language (continuously updated)
Special register C51 / C52