ASP.NET系列:自定义配置节点的复用

appSettings太简单,为每个程序自定义配置节点太复杂,因此要解决app.config&web.config自定义配置的复用问题。

1.读取不依赖SectionName,根节点可以定义为任何名称。

2.足够简单,配置项采用name value的形式;足够复杂,采用树型结构,每个节点都可以有多个配置项和子节点。

3.使用简单,采用路径简化配置项的读取。如: config.Get<string>("root.sub.item-test")。

一、调用方式:

1.配置文件:

<?xml version="1.0" encoding="utf-8" ?>
<configuration><configSections><section name="node" type="Onion.Configuration.AppConfig.ConfigSection,Onion.Configuration" /></configSections><node name="root"><items><item name="version" value="1.0.0.1" /></items><nodes><node name="runtime"><items><item name="debug" value="false" /><item name="ioc" value="IoC.Contianer.StructureMapIoC" /></items></node><node name="upload"><items><item name="auth" value="true" /><item name="path" value="~/upload" /><item name="url" value="~/Upload/Index" /></items></node><node name="captcha"><items><item name="timeout" value="3000" /><item name="url" value="~/Captcha/Index" /></items></node><node name="oauth2"><items><item name="disabled" value ="false" /><item name="callback" value ="/Home/ExternalLoginCallBack?ProviderName=" /></items><nodes><node name="qqclient"><items><item name="disabled" value="false" /><item name="method" value="get" /><item name="key" value="9233e24d" /><item name="secret" value="1ac35907-7cfa-4079-975c-959b98d23a95" /></items></node><node name="weiboclient"><items><item name="disabled" value="true" /><item name="method" value="post" /><item name="key" value="0cdea8f3" /><item name="secret" value="dc679dbb-7e75-44f7-a99e-5359259fc94b" /></items></node></nodes></node></nodes></node>
</configuration>

2.调用代码:

[Fact]public void Tests(){var config = new AppConfigAdapter();Assert.True(config.Get<string>("version") == "1.0.0.1");Assert.True(config.Get<bool>("runtime.debug") == false);Assert.True(config.Get<string>("runtime.ioc") == "IoC.Contianer.StructureMapIoC");Assert.True(config.Get<bool>("upload.auth") == true);Assert.True(config.Get<string>("upload.path") == "~/upload");Assert.True(config.Get<string>("upload.url") == "~/Upload/Index");Assert.True(config.Get<int>("captcha.timeout") == 3000);Assert.True(config.Get<string>("captcha.url") == "~/Captcha/Index");Assert.True(config.Get<bool>("oauth2.disabled") == false);Assert.True(config.Get<string>("oauth2.callback") == "/Home/ExternalLoginCallBack?ProviderName=");Assert.True(config.GetNode("oauth2").Nodes.Any(o => o.GetItem<bool>("disabled")));foreach (var node in config.GetNode("oauth2").Nodes){if (node.Name == "qqclient"){Assert.True(node.GetItem<bool>("disabled") == false);Assert.True(node.GetItem<string>("method") == "get");Assert.True(node.GetItem<string>("key") == "9233e24d");Assert.True(node.GetItem<string>("secret") == "1ac35907-7cfa-4079-975c-959b98d23a95");}else if (node.Name == "weiboclient"){Assert.True(node.GetItem<bool>("disabled") == true);Assert.True(node.GetItem<string>("method") == "post");Assert.True(node.GetItem<string>("key") == "0cdea8f3");Assert.True(node.GetItem<string>("secret") == "dc679dbb-7e75-44f7-a99e-5359259fc94b");}}}

二、接口定义:

1.配置项定义:IItem接口定义最基础的配置项,只包含Name和Value属性。

public interface IItem
{string Name { get; set; }string Value { get; set; }
}

2.配置节点定义:INode接口定义了配置节点的树形结构

public interface INode
{string Name { get; set; }IEnumerable<IItem> Items { get; set; }IEnumerable<INode> Nodes { get; set; }string GetItem(string itemName);T GetItem<T>(string itemName);
}

 

3.读取接口定义:IConfig接口定义了配置节点和配置项的读取

public interface IConfig
{INode GetNode(string nodeName);string Get(string nameOrPath);T Get<T>(string nameOrPath);
}

以上3个接口定义了所有的逻辑。

三、接口实现:

1.自定义ItemElement(IItem)和ItemElementCollection用于实现单个节点的配置项读取。

    public class ItemElement : ConfigurationElement, IItem{[ConfigurationProperty("name", IsRequired = true)]public string Name{get { return Convert.ToString(this["name"]); }set { this["name"] = value; }}[ConfigurationProperty("value", IsRequired = true)]public string Value{get { return Convert.ToString(this["value"]); }set { this["value"] = value; }}}public class ItemElementCollection : ConfigurationElementCollection, IEnumerable<IItem>{protected override ConfigurationElement CreateNewElement(){return new ItemElement();}protected override object GetElementKey(ConfigurationElement element){return ((ItemElement)element).Name;}public new IEnumerator<IItem> GetEnumerator(){for (int i = 0; i < base.Count; i++){yield return base.BaseGet(i) as IItem;}}}
View Code

 

2.自定义NodeElement(INode)和NodeElementCollection用于实现节点树功能。

    public class NodeElement : ConfigurationElement, INode{[ConfigurationProperty("name", IsRequired = true)]public string Name{get { return Convert.ToString(this["name"]); }set { this["name"] = value; }}[ConfigurationProperty("items")][ConfigurationCollection(typeof(ItemElementCollection), AddItemName = "item")]public ItemElementCollection ItemElements{get{return this["items"] as ItemElementCollection;}set { this["items"] = value; }}[ConfigurationProperty("nodes")][ConfigurationCollection(typeof(NodeElementCollection), AddItemName = "node")]public NodeElementCollection NodeElements{get{return this["nodes"] as NodeElementCollection;}set { this["nodes"] = value; }}public IEnumerable<IItem> Items{get{return this["items"] as ItemElementCollection;}set { this["items"] = value; }}public IEnumerable<INode> Nodes{get{return this["nodes"] as NodeElementCollection;}set { this["nodes"] = value; }}public string GetItem(string itemName){return this.Items.FirstOrDefault(o => o.Name == itemName)?.Value;}public T GetItem<T>(string itemName){return (T)Convert.ChangeType(this.GetItem(itemName), typeof(T));}}public class NodeElementCollection : ConfigurationElementCollection, IEnumerable<INode>{protected override ConfigurationElement CreateNewElement(){return new NodeElement();}protected override object GetElementKey(ConfigurationElement element){return ((NodeElement)element).Name;}public new IEnumerator<INode> GetEnumerator(){for (int i = 0; i < base.Count; i++){yield return base.BaseGet(i) as INode;}}}
View Code

 

3.自定义ConfigSection实现配置节点和配置项读取。

    public class ConfigSection : ConfigurationSection, INode{[ConfigurationProperty("name", IsRequired = true)]public string Name{get { return Convert.ToString(this["name"]); }set { this["name"] = value; }}[ConfigurationProperty("items")][ConfigurationCollection(typeof(ItemElementCollection), AddItemName = "item")]public ItemElementCollection ItemElements{get{return this["items"] as ItemElementCollection;}set { this["items"] = value; }}[ConfigurationProperty("nodes")][ConfigurationCollection(typeof(NodeElementCollection), AddItemName = "node")]public NodeElementCollection NodeElements{get{return (NodeElementCollection)this["nodes"];}set { this["nodes"] = value; }}public IEnumerable<IItem> Items{get{return this["items"] as ItemElementCollection;}set { this["items"] = value; }}public IEnumerable<INode> Nodes{get{return (NodeElementCollection)this["nodes"];}set { this["nodes"] = value; }}public string GetItem(string itemName){return this.Items.FirstOrDefault(o => o.Name == itemName)?.Value;}public T GetItem<T>(string itemName){return (T)Convert.ChangeType(this.GetItem(itemName), typeof(T));}}
View Code

 

4.自定义AppConfigAdapter实现IConfig接口。

    public class AppConfigAdapter : IConfig{private INode _section;public AppConfigAdapter(){var sectionName = (HostingEnvironment.IsHosted ? WebConfigurationManager.OpenWebConfiguration("~") : ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)).Sections.Cast<ConfigurationSection>().FirstOrDefault(o => o.SectionInformation.Type.IndexOf("Onion.Configuration.AppConfig.ConfigSection") != -1).SectionInformation.Name ?? "Node";_section = (INode)ConfigurationManager.GetSection(sectionName);}public INode GetNode(string nodeName){return this.GetNode(nodeName, this._section);}public string Get(string nameOrPath){if (nameOrPath.IndexOf('.') == -1){return this._section.Items.FirstOrDefault(o => o.Name == nameOrPath)?.Value;}var nodeItemPath = nameOrPath.Split('.');var node = this.GetNode(nodeItemPath.FirstOrDefault());var nodeNameList = nodeItemPath.Skip(1).Take(nodeItemPath.Length - 2);if (node != null){foreach (var item in nodeNameList){if (node.Nodes.Any(o => o.Name == item)){node = node.Nodes.FirstOrDefault(o => o.Name == item);}else{throw new System.ArgumentException(string.Format("node name {0} error", item));}}return node.Items.FirstOrDefault(o => o.Name == nodeItemPath.LastOrDefault()).Value;}return null;}public T Get<T>(string nameOrPath){var value = this.Get(nameOrPath);return (T)Convert.ChangeType(value, typeof(T));}#region privateprivate INode GetNode(string nodeName, INode node){INode result = null;if (node.Name == nodeName){return node;}else if (node.Nodes.Any()){foreach (var item in node.Nodes){result = GetNode(nodeName, item);if (result != null){break;}}}return result;}#endregion private}
View Code

 

Nuget:https://www.nuget.org/packages/Onion.Configuration/

转载于:https://www.cnblogs.com/easygame/p/5051592.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/272608.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Web的26项基本概念和技术

Web开发是比较费神的&#xff0c;需要掌握很多很多的东西&#xff0c;特别是从事前端开发的朋友&#xff0c;需要通十行才行。今天&#xff0c;本文向初学者介绍一些Web开发中的基本概念和用到的技术&#xff0c;从A到Z总共26项&#xff0c;每项对应一个概念或者技术。Internet…

android 引入 .so,android studio引入so库方法(示例代码)

在Android Studio中引入so库&#xff0c;只需在app/jniLibs下放入so文件&#xff0c;然后在Module的build.gradle中加入&#xff1a;sourceSets {main {jniLibs.srcDirs [‘libs‘]}}完整的build.gradle如下&#xff1a;apply plugin: ‘com.android.library‘android {compil…

BZOJ3670: [Noi2014]动物园

Description 近日&#xff0c;园长发现动物园中好吃懒做的动物越来越多了。例如企鹅&#xff0c;只会卖萌向游客要吃的。为了整治动物园的不良风气&#xff0c;让动物们凭自己的真才实学向游客要吃的&#xff0c;园长决定开设算法班&#xff0c;让动物们学习算法。 某天&#x…

NSPredicate的用法、数组去重、比较...

一般来说这种情况还是蛮多的&#xff0c;比如你从文件中读入了一个array1&#xff0c;然后想把程序中的一个array2中符合array1中内容的元素过滤出来。 1&#xff09;例子一&#xff0c;一个循环 NSArray *arrayFilter [NSArray arrayWithObjects:"pict", "bla…

android one指纹解锁,小米用屏幕内指纹扫描仪准备了两部Android One手机

2017年9月发布时&#xff0c;小米米A1几乎成功一夜成名。小西米去年夏天推出了Mi A2和Mi A2 Lite。现在&#xff0c;正如XDA开发者所揭示的那样&#xff0c;中国品牌正在筹备第三代产品阵容。代号为“bamboo_sprout”和“cosmos_sprout” - 所有Android One智能手机都包含代号为…

hive日志位置(日志定位报错:Failed with exception Unable to move sourcehdfs://namenode/tmp/hive-pmp_bi/h)...

Hive中的日志分为两种 1. 系统日志&#xff0c;记录了hive的运行情况&#xff0c;错误状况。 2. Job 日志&#xff0c;记录了Hive 中job的执行的历史过程。日志查看方法 1&#xff0c;在本地运行机器上 hive日志存储位置在本机上&#xff0c;不是hadoop上&#xff1a;在hive/co…

控制算法用c语言实现的,PID控制算法的C语言实现(完整版)

【实例简介】该文件里面还有各种改进的PID的算法&#xff0c;比如变积分控制等【实例截图】【核心代码】具体 PID 实现代码如下&#xff1a;pid.Kp0.4;pid.Ki0.2;//增加了积分系数pid.Kd0.2;float PID_realize(float speed){float index;pid.SetSpeedspeed;pid.errpid.SetSpeed…

《挑战程序设计竞赛》2.2 贪心法-其它 POJ3617 3069 3253 2393 1017 3040 1862 3262

POJ3617 Best Cow Line 题意 给定长度为N的字符串S&#xff0c;要构造一个长度为N的字符串T。起初&#xff0c;T是一个空串&#xff0c;随后反复进行下列任意操作&#xff1a; 从S的头部&#xff08;或尾部&#xff09;删除一个字符&#xff0c;加到T的尾部 目标是构造字典序…

easyui dialog的一个小坑

问题描述&#xff1a;1、html<div id"dig" style"padding:10px;width:500px;height:300px;font-family:微软雅黑;font-size:16px;"> Dialog Content. </div> 2、js$("#dig").css("display", "block");$(#dig).d…

android rxbus 一个页面监听,Android RxBus的使用

RxBus的核心功能是基于Rxjava的&#xff0c;在RxJava中有个Subject类&#xff0c;它继承Observable类&#xff0c;同时实现了Observer接口&#xff0c;因此Subject可以同时担当订阅者和被订阅者的角色&#xff0c;这里我们使用Subject的子类PublishSubject来创建一个Subject对象…

AngularJS $q

updatePushIdfunction($q,pushid) { var d$q.defer(); var data {pushid:pushid}; server.api("/updateRId",data).success(function(res){ if(res.resultcode1){ d.resolve(更新成功.);…

C# 如何转换生成长整型的时间

这个数字字符串就是我们平常所说的时间戳。什么是时间戳&#xff1f;时间戳&#xff08;timestamp&#xff09;&#xff0c;通常是一个字符序列&#xff0c;唯一地标识某一刻的时间。时间戳是指格林威治时间1970年01月01日00时00分00秒(北京时间1970年01月01日08时00分00秒)起至…

html自动滑动轮播代码,html+css+js 实现自动滑动轮播图

轮播图*{margin: 0 auto;padding: 0;list-style: none; //去圆点}.one {width: 1200px;height:350px;margin: 0 auto;overflow: hidden; //设定好的宽度多余的进行隐藏}.one ul{width: 3600px;position: relative;}.one ul li{float: left; //图片浮动}.two ul li { …

程序员必定会爱上的10款软件

目录 第一款&#xff1a;TrueCrypt 第二款&#xff1a;Soureinsight 第三款&#xff1a;Sublime 第四款&#xff1a;Mindmanager 第五款&#xff1a;MarkdownPad 第六款&#xff1a;Beyond compare 第七款&#xff1a;Vim 第八款&#xff1a;Wireshark 第九款&#xff1a;Fiddl…

html定义字体纵向对齐,HTML5 Canvas的文本如何实现垂直对齐

垂直对齐&#xff0c;使用CSS很容易实现&#xff0c;如果想在HTML5 Canvas中实现垂直对齐&#xff0c;如何设置呢&#xff0c;这就是今天要分享的笔记。HTML画布垂直对齐的文本&#xff0c;我们可以使用的textBaseline在画布范围内的属性值。textBaseline可以设置以下值之一 &a…

深度学习方法:受限玻尔兹曼机RBM(三)模型求解,Gibbs sampling

欢迎转载&#xff0c;转载请注明&#xff1a;本文出自Bin的专栏blog.csdn.net/xbinworld。 技术交流QQ群&#xff1a;433250724&#xff0c;欢迎对算法、技术、应用感兴趣的同学加入。 接下来重点讲一下RBM模型求解方法&#xff0c;其实用的依然是梯度优化方法&#xff0c;但是…

推荐一款PC端的远程软件-Remote Utilities

远程控制软件非常之多&#xff0c;但小编自己用过的就那么3个&#xff1a;teamviewer&#xff1a;在家远程办公时基本上都靠它连回公司的电脑&#xff0c;速度快、稳定、不需要公网IP。vnc&#xff1a;要开启vpn才能连回公司的网络&#xff0c;速度够快。系统自带远程桌面&…

原生js追加html代码,原生js实现给指定元素的后面追加内容

复制代码 代码如下:var header1 document.getElementById("header");var p document.createElement("p"); // 创建一个元素节点insertAfter(p,header1); // 因为js没有直接追加到指定元素后面的方法 所以要自己创建一个方法function insertAfter( newEle…

这些才是Win10真正好用之处:瞬对Win7无爱

自从将家里的笔电、台式机全部升级到Win10之后&#xff0c;小编可是切切实实感受到了它的强大&#xff0c;非常多的改进、非常多人性化的设计。和之前的测试版不同&#xff0c;作为主力系统后自然要匹配日常的工作。很多设置、操作也要顺应以前的使用习惯。经过这几天折腾&…

html5 保存 搜索历史,html5 – 如何有效处理Dart中的浏览器历史记录(即后退按钮)?...

HTML5定义了用于操作历史记录的新API,允许您在不重新加载窗口的情况下更改位置.有一篇关于Dive Into HTML5的精彩文章,展示了如何使用历史API在单页面应用中模拟多页面导航.它很容易翻译成Dart.在带导航的单页应用程序中,我通常设置客户端代码的方式类似于在服务器上设置RoR或D…