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…

BZOJ3670: [Noi2014]动物园

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

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

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

控制算法用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…

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…

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;速度够快。系统自带远程桌面&…

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

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

Win10非常好用的6个使用技巧

很多人已经用上了Win10系统&#xff0c;为了提高使用效率掌握使用技巧尤为重要&#xff0c;今天我为大家分享win10的6个使用技巧。第一个&#xff1a;快速查找文件&#xff08;win键E&#xff09;想要打开某个文件&#xff0c;直接使用这个快捷键就可以打开资源管理器&#xff…

servlet html登录,Servlet实现用户登录

1、登录过程分析&#xff1a;通过表单收集用户的数据&#xff0c;Servlet通过request对象获得用户提交的数据&#xff0c;服务器还需要从数据库中通过sql语句查询有没有表单提交的数据中的用户。有则登录成功&#xff0c;否则&#xff0c;登录失败。2、工程结构&#xff1a;3、…

C#中AssemblyInfo.cs文件详解

1、.Net工程的Properties文件夹下自动生成一个名为AssemblyInfo.cs的文件&#xff0c;一般情况下我们很少直接改动该文件。但我们实际上通过另一个形式操作该文件。那就是通过在鼠标右键点击项目的属性进入“应用程序”->“程序集信息”&#xff0c;然后修改信息。2、通过特…

html复制文字兼容手机,JavaScript+Html5实现按钮复制文字到剪切板功能(手机网页兼容)...

新学习JavaScript&#xff0c;就碰到这么一个需求&#xff0c;几乎网上的方法都试过了。写出了总结下使用的方法&#xff1a;clipboard插件下载地址&#xff1a;https://github.com/zenorocha/clipboard.js/tree/master引入插件&#xff1a;目录\clipboard.js-master\dist\clip…

Memcached的基础梳理

1 、Memcached 概念官方解释如下&#xff1a;What is Memcached?Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.Me…

html5 canvas 笔记五(合成与裁剪)

组合 Compositing globalCompositeOperation syntax: globalCompositeOperation type 注意&#xff1a;下面所有例子中&#xff0c;蓝色方块是先绘制的&#xff0c;即“已有的 canvas 内容”&#xff0c;红色圆形是后面绘制&#xff0c;即“新图形”。 source-over  这是默认…

一个能够编写、运行SQL查询并可视化结果的Web应用:SqlPad

SqlPad 是一个能够用于编写、运行SQL查询并可视化结果的Web应用。支持 PostgreSQL、MySQL 和 SQL Server。SqlPad 目前仅适合单个团队在内网中使用&#xff0c;它直接通过网络连接到数据库服务器&#xff0c;任何人可以在上面执行任意 SQL 语句。安装首先安装 Node.js.安装好No…

Web前端开发框架对比

近几年随着 jQuery、Ext 以及 CSS3 的发展&#xff0c;以 Bootstrap 为代表的前端开发框架如雨后春笋般挤入视野&#xff0c;可谓应接不暇。不论是桌面浏览器端还是移动端都涌现出很多优秀的框架&#xff0c;极大丰富了开发素材&#xff0c;也方便了大家的开发。这些框架各有特…