背景

对于编译型应用程序来说,参数化程序行为是非常有必要的,.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:自定义配置节的更多相关文章

  1. C#创建自定义配置节

    在.Net应用程序中,我们经常看到VS为我们生成的项目工程中都会含有nfig或者nfig这样的文件.这个文件就是我们所说的应用程序配置文件.在这个文件里面记述着一些与我们的应用程序相关的信息,如:数据 ...

  2. C#如何使用和开发自定义配置节

    在日常的程序设计中,如何灵活和巧妙地运用配置信息是一个成功的设计师的首要选择.这不仅是为了程序设计得更灵活性和可扩展性,也是为了让你的代码给人以清新的感觉.程序中的配置信息一般放在应用程序的app.c ...

  3. 使用 ConfigurationSection 创建自定义配置节

    我们可以通过用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集,要完成这一功能,我们必须实现继承System.Configuration.ConfigurationSection 类来 ...

  4. C# App.config 自定义 配置节

    1)App.config <?xml version="1.0" encoding="utf-8" ?><configuration>  ...

  5. C# App.config 自定义 配置节 报错“配置系统未能初始化” 解决方法

    App.config,结果运行的时候出现了 "配置系统未能初始化" 的错误.找了半天才发现是下面的原因造成的: "如果配置文件中包含configSections元素,则c ...

  6. C# App.config 自定义 配置节 出现的问题:配置系统未能初始化

    C# 读取app.config配置文件 节点键值,提示 "配置系统未能初始化" 错误的解决方案 新建C#项目,在app.config中添加了appSettings项,运行时出现&q ...

  7. ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合

    核心代码 using System; using System.Data; using System.Configuration; using System.Web; using System.Web ...

  8. ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节

    主要代码,一定要继续System.Configuration.ConfigurationSection,具体的节点名称可以自行修改 using System; using System.Data; u ...

  9. App.config 中读写appSettings、system.serviceModel终结点,以及自定义配置节

    转自:http://blog.csdn.net/chelen_jak/article/details/8190795 感觉写的很好,推荐

随机推荐

  1. 20175225《java程序设计》第五周学习总结

    20175225 2018-2019-2 <Java程序设计>第5周学习总结 教材学习内容总结 1.接口体中包含常量的声明(没有变量)和抽象方法两部分.接口体中只有抽象方法,没有普通的方法 ...

  2. spring-web.xml 模板

    ssm模板 <?xml version="1.0" encoding="UTF-8"?>  <beans xmlns="http:/ ...

  3. HDOJ题目分类

    模拟题, 枚举1002 1004 1013 1015 1017 1020 1022 1029 1031 1033 1034 1035 1036 1037 1039 1042 1047 1048 104 ...

  4. 在centos中修改yum源为阿里源

    cd /etc/yum.repos.d 备份旧的配置文件:mv CentOS-Base.repo CentOS-Base.repo.bak 下载阿里源的文件: wget -O CentOS-Base. ...

  5. (转)jquery serialize表单序列化,当radio或checkbox 未选中时,没有序列化到对象中的原因分析和解决方案 - ghostsf

    相信很多人都用过jq的表单序列化serialize()方法,因为这能很方便地帮你把表单里所有的非禁用输入控件序列化为 key/value 对象,不需要你再去一个个地拼接参数了. 这是一个很好用的函数, ...

  6. 【PAT】1060 Are They Equal (25)(25 分)

    1060 Are They Equal (25)(25 分) If a machine can save only 3 significant digits, the float numbers 12 ...

  7. win10下 Jupyter Notebook不运行python 3怎么办?

    Jupyter Notebook不运行python 3怎么办? 内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用 我已经安装了Python 2的Anaco ...

  8. CSS3利用一个div实现内圆角边框效果

    *首先要清楚的是,box-shadow的形状会随着border-radius变化.下面的例子可以证明: <!doctype html> <html lang="en&quo ...

  9. POJ1274 The Perfect Stall[二分图最大匹配 Hungary]【学习笔记】

    The Perfect Stall Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 23911   Accepted: 106 ...

  10. BZOJ.5312.冒险(线段树)

    题目链接 \(Description\) 维护一个序列,支持区间and/or一个数.区间查询最大值. \(Solution\) 维护区间最大值?好像没什么用,修改的时候和暴力差不多. 我们发现有时候区 ...