.NET:自定义配置节
背景
对于编译型应用程序来说,参数化程序行为是非常有必要的,.NET有其标准的配置方法,我们可以可以扩展。
示例
代码
using System;
using System.Collections;
using System.Text;
using System.Configuration;
using System.Xml; namespace YEA.Infrastructure.Gateway.Config
{
public enum ExchangeType { direct, topic, fanout };
public class Exchange : ConfigurationElement
{
[ConfigurationProperty("name", DefaultValue = "", IsRequired = true)]
public string Name
{
get { return (string) this["name"]; }
set { this["name"] = value; }
}
[ConfigurationProperty("connection", DefaultValue = "", IsRequired = true)]
public string Connection
{
get { return (string)this["connection"]; }
set { this["connection"] = value; }
}
[ConfigurationProperty("type", DefaultValue = "direct", IsRequired = true)]
public ExchangeType Type
{
get { return (ExchangeType)this["type"]; }
set { this["type"] = value; }
}
[ConfigurationProperty("autodelete", DefaultValue= true, IsRequired = false)]
public bool AutoDelete
{
get { return (bool)this["autodelete"]; }
set { this["autodelete"] = value; }
}
[ConfigurationProperty("durable", DefaultValue = false, IsRequired = false)]
public bool Durable
{
get { return (bool)this["durable"]; }
set { this["durable"] = value; }
}
}
public class ExchangeCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType
{
get
{
return ConfigurationElementCollectionType.AddRemoveClearMap;
}
}
protected override ConfigurationElement CreateNewElement()
{
return new Exchange();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((Exchange)element).Name;
}
public new string AddElementName
{
get { return base.AddElementName; }
set { base.AddElementName = value; }
}
public new string ClearElementName
{
get { return base.ClearElementName; }
set { base.ClearElementName = value; } } public new string RemoveElementName
{
get { return base.RemoveElementName; }
} public new int Count
{
get { return base.Count; }
} public Exchange this[int index]
{
get
{
return (Exchange)BaseGet(index);
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
} new public Exchange this[string Name]
{
get { return (Exchange)BaseGet(Name); }
} public int IndexOf(Exchange exchange)
{
return BaseIndexOf(exchange);
} public void Add(Exchange exchange)
{
BaseAdd(exchange);
// Add custom code here.
} protected override void BaseAdd(ConfigurationElement element)
{
BaseAdd(element, false);
// Add custom code here.
} public void Remove(Exchange exchange)
{
if (BaseIndexOf(exchange) >= )
BaseRemove(exchange.Name);
} public void RemoveAt(int index)
{
BaseRemoveAt(index);
} public void Remove(string name)
{
BaseRemove(name);
} public void Clear()
{
BaseClear();
// Add custom code here.
}
}
public class AMQPObjectsDeclarationSection : ConfigurationSection
{
[ConfigurationProperty("ExchangeList", IsDefaultCollection = false)]
public ExchangeCollection ExchangeList
{
get
{
ExchangeCollection exchanges = (ExchangeCollection)this["ExchangeList"];
return exchanges;
}
}
[ConfigurationProperty("QueueList", IsDefaultCollection = false)]
public QueueCollection QueueList
{
get
{
QueueCollection queue = (QueueCollection)this["QueueList"];
return queue;
}
}
[ConfigurationProperty("BindingList", IsDefaultCollection = false)]
public BindingCollection BindingList
{
get
{
BindingCollection binding = (BindingCollection)this["BindingList"];
return binding;
}
} protected override void DeserializeSection(System.Xml.XmlReader reader)
{
base.DeserializeSection(reader);
// You can add custom processing code here.
} protected override string SerializeSection(
ConfigurationElement parentElement,
string name, ConfigurationSaveMode saveMode)
{
string s =
base.SerializeSection(parentElement,
name, saveMode);
// You can add custom processing code here.
return s;
} }
}
最终XML配置
App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="AMQPConnection">
<section name="ConnectionSettings"
type="YEA.Infrastructure.Gateway.Config.ConnectionSection, YEA.Infrastructure.Gateway"></section>
</sectionGroup>
<sectionGroup name="AMQPAdmin">
<section name="AMQPObjectsDeclaration"
type="YEA.Infrastructure.Gateway.Config.AMQPObjectsDeclarationSection, YEA.Infrastructure.Gateway"
allowLocation="true"
allowDefinition="Everywhere"></section>
</sectionGroup> </configSections>
<AMQPConnection >
<ConnectionSettings configSource="Config\amqp.connection.config"/>
</AMQPConnection>
<AMQPAdmin>
<AMQPObjectsDeclaration configSource="Config\amqp.objects.config"/>
</AMQPAdmin>
<appSettings >
<add key="SleepTime" value="0"></add>
<!--Mode = ["Receiver","Transmitter"]-->
<add key="Mode" value="Receiver"></add>
<add key="DummyFile" value="C:\logs\YEA\Monitor\LogService.txt"></add>
<add key="notificationToEmail" value="ruben.rotteveel@chamberlain.com"/>
<add key="notificationFromEmail" value="webmaster@chamberlain.com"/>
</appSettings>
</configuration>
amqp.connection.config
<?xml version="1.0" encoding="utf-8" ?>
<ConnectionSettings>
<ConnectionList>
<add name="Connection" server="localhost" username="guest" password="guest"></add>
</ConnectionList>
<PublisherList>
<add name="orderPublisher" connection="Connection" exchange="orders" ></add>
<add name="notificationPublisher" connection="Connection" exchange="notificationExchange"></add>
<add name="logPublisher" connection="Connection" exchange="logExchange"></add>
</PublisherList>
<AsyncReceiverList>
<add name="orderReceiver" connection="Connection" queue="uk_orders, marketingemails, Accounting, CustomerService" maxthreads="40"></add>
<add name="notificationReceiver" connection="Connection" queue="notificationQueue" maxthreads ="1"></add>
<add name="logReceiver" connection="Connection" queue="logQueue" maxthreads ="1"></add>
</AsyncReceiverList>
</ConnectionSettings>
amqp.objects.config
<?xml version="1.0" encoding="utf-8" ?>
<AMQPObjectsDeclaration>
<ExchangeList>
<add name="orders" connection="Connection" type="topic" autodelete="false" durable="true"></add>
<add name="shipments" connection="Connection" type ="topic" autodelete="false" durable="true"></add>
<add name="logExchange" connection="Connection" type="topic" autodelete="false" durable="true"></add>
<add name="notificationExchange" connection="Connection" type="topic" autodelete="false" durable="true"></add>
</ExchangeList>
<QueueList>
<add name="uk_orders" connection="Connection" autodelete="false" durable="true"></add>
<add name="us_orders" connection="Connection" autodelete="false" durable="true"></add>
<add name="marketingemails" connection="Connection" autodelete ="false" durable="true"></add>
<add name="Accounting" connection="Connection" autodelete="false" durable="true" ></add>
<add name="CustomerService" connection="Connection" autodelete="false" durable="true" ></add>
<add name="logQueue" connection="Connection" autodelete="false" durable="true"></add>
<add name="notificationQueue" connection="Connection" autodelete="false" durable="true"></add>
</QueueList>
<BindingList>
<add queue="uk_orders" connection="Connection" exchange="orders" subscriptionkey="order.uk.#"></add>
<add queue="us_orders" connection="Connection" exchange="orders" subscriptionkey="order.us.#"></add>
<add queue="marketingemails" connection="Connection" exchange="shipments" subscriptionkey="#" ></add>
<add queue="marketingemails" connection="Connection" exchange="orders" subscriptionkey="#" ></add>
<add queue="Accounting" connection="Connection" exchange="shipments" subscriptionkey="#" ></add>
<add queue="Accounting" connection="Connection" exchange="orders" subscriptionkey="#" ></add>
<add queue="CustomerService" connection="Connection" exchange="shipments" subscriptionkey="#" ></add>
<add queue="CustomerService" connection="Connection" exchange="orders" subscriptionkey="#" ></add>
<add queue="logQueue" connection="Connection" exchange="logExchange" subscriptionkey="#"></add>
<add queue="notificationQueue" connection="Connection" exchange="notificationExchange" subscriptionkey="#"></add>
</BindingList>
</AMQPObjectsDeclaration>
读取配置
var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
var objects = config.GetSection("AMQPAdmin/AMQPObjectsDeclaration") as AMQPObjectsDeclarationSection;
备注
简单的使用配置并不是最好的方式,比如:在控制台程序中,最好提供两种方式:通过命令行参数和配置结合,然后采用适当的优先级处理。另外,采用JSON配置可能会更简单一点。
.NET:自定义配置节的更多相关文章
- C#创建自定义配置节
在.Net应用程序中,我们经常看到VS为我们生成的项目工程中都会含有nfig或者nfig这样的文件.这个文件就是我们所说的应用程序配置文件.在这个文件里面记述着一些与我们的应用程序相关的信息,如:数据 ...
- C#如何使用和开发自定义配置节
在日常的程序设计中,如何灵活和巧妙地运用配置信息是一个成功的设计师的首要选择.这不仅是为了程序设计得更灵活性和可扩展性,也是为了让你的代码给人以清新的感觉.程序中的配置信息一般放在应用程序的app.c ...
- 使用 ConfigurationSection 创建自定义配置节
我们可以通过用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集,要完成这一功能,我们必须实现继承System.Configuration.ConfigurationSection 类来 ...
- C# App.config 自定义 配置节
1)App.config <?xml version="1.0" encoding="utf-8" ?><configuration> ...
- C# App.config 自定义 配置节 报错“配置系统未能初始化” 解决方法
App.config,结果运行的时候出现了 "配置系统未能初始化" 的错误.找了半天才发现是下面的原因造成的: "如果配置文件中包含configSections元素,则c ...
- C# App.config 自定义 配置节 出现的问题:配置系统未能初始化
C# 读取app.config配置文件 节点键值,提示 "配置系统未能初始化" 错误的解决方案 新建C#项目,在app.config中添加了appSettings项,运行时出现&q ...
- ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合
核心代码 using System; using System.Data; using System.Configuration; using System.Web; using System.Web ...
- ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节
主要代码,一定要继续System.Configuration.ConfigurationSection,具体的节点名称可以自行修改 using System; using System.Data; u ...
- App.config 中读写appSettings、system.serviceModel终结点,以及自定义配置节
转自:http://blog.csdn.net/chelen_jak/article/details/8190795 感觉写的很好,推荐
随机推荐
- vue项目使用vw单位适配移动端方法
传送门: https://blog.csdn.net/zjw0742/article/details/79337336
- PHP转盘抽奖算法
流程: 1.拼装奖项数组 2.计算概率 3.返回中奖情况 代码如下: 中奖概率 ' v ' 可以在后台设置,传到此方法中,注意传整数 function get_gift(){ //拼装奖项数组 // ...
- HDR 视频编码
前转换以及后转换:-f xxx.cfg (以及注意工作目录以及路径名/和//) HEVC视频编码:-c xxx.cfg -c xx.cfg(视频的配置文件)
- VMware下三种网络连接模式
VMware下三种网络连接模式 Bridged(桥接模式) 在桥接模式下,VMware虚拟出来的操作系统就像是局域网中的一独立的主机,它可以访问该类网段内任何一台机器. 桥接网络环境下需要做到: 手动 ...
- mysql 日期操作 增减天数、时间转换、时间戳(转换)
http://hi.baidu.com/juntao_li/item/094d78c6ce1aa060f6c95d0b MySQL datediff(date1,date2):两个日期相减 date1 ...
- 扩展BootstrapTable的treegrid功能
扩展BootstrapTable的treegrid功能 阅读目录 一.效果预览 二.代码示例 三.组件需要完善的地方 四.总结 正文 前言:上篇 JS组件系列——自己动手封装bootstrap-tr ...
- bzoj [ZJOI2008]生日聚会Party
思路:dp, 用dp[ i ][ j ][ u ][ v ] 表示, 有n个人,其中有j个是男生,后缀区间中男生人数减去女生人数的最大值为u, 女生人数减去男生人数 的最大值为v, 然后就能写出状态转 ...
- JAVA-Exception&Error
JAVA--Exception&Error 在万物皆对象的JAVA中,先让我们看看Exception和Error的地位吧:
- linux学习笔记-2.常用命令
说明:安装linux时,创建一个luao用户,然后使用root用户登陆系统 1.进入到用户根目录 cd ~ 或 cd cd / 返回到根目录 2.查看当前所在目录 pwd 3.进入到luao用户根目录 ...
- InnoDB的锁机制浅析(二)—探索InnoDB中的锁(Record锁/Gap锁/Next-key锁/插入意向锁)
Record锁/Gap锁/Next-key锁/插入意向锁 文章总共分为五个部分: InnoDB的锁机制浅析(一)-基本概念/兼容矩阵 InnoDB的锁机制浅析(二)-探索InnoDB中的锁(Recor ...