背景

对于编译型应用程序来说,参数化程序行为是非常有必要的,.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. Python常见面试(习题)——水仙花数

    今天,给大家分享一个习题. 用python输出100到1000以内的水仙花数. 相信很多小伙伴都听到过,或者遇到过这个题目. 那么今天就来带大家做一做这道题. 首先,我们要知道什么是水仙花数, (@_ ...

  2. SqlServer中 SET DATEFIRST更改

    在 SQL Server 中默认情况下,每周的开始都是从周日开始算起的,如果默认星期一呢? 这里有三种方式可以解决这个问题: 一:直接通过 SET DATEFIRST VALUE 来更改重新生成新的 ...

  3. 深度剖析:PHP中json_encode与json_decode

    一.json_encode() 对变量进行JSON编码, 语法: json_encode ( $value [, $options = 0 ] ) 注意:1.$value为要编码的值,且该函数只对UT ...

  4. 将prometheus采集的数据远程存储到influxdb中

    这个比较简单, https://docs.influxdata.com/influxdb/v1.7/supported_protocols/prometheus 只需要更改prometheus.yam ...

  5. Codeforces 336D Dima and Trap Graph 并查集

    Dima and Trap Graph 枚举区间的左端点, 然后那些左端点比枚举的左端点小的都按右端点排序然后并查集去check #include<bits/stdc++.h> #defi ...

  6. React Native之原生模块的开发(Android)学习笔记

      目录 1.为什么我们需要原生模块开发 2.开发Android原生模块的主要流程 3.原生模块开发实战   1.为什么我们需要原生模块开发? 我们在用RN开发App的时候,有时候需要用到一些原生模块 ...

  7. JedisConnectionException: java.net.ConnectException: Connection refused

    出现问题 我遇到的一个问题,在连接redis的时候出现了错误!错误如下: JedisConnectionException: java.net.ConnectException: Connection ...

  8. codeforces_1092c

    title: codeforces_1092c date: 2018-12-24 19:42:23 tags: acm 刷题 概述 一道有关字符串前缀后缀的题,,,自己迟早要坑在这字符串的题上,,,一 ...

  9. InnoDB的锁机制浅析(五)—死锁场景(Insert死锁)

    可能的死锁场景 文章总共分为五个部分: InnoDB的锁机制浅析(一)-基本概念/兼容矩阵 InnoDB的锁机制浅析(二)-探索InnoDB中的锁(Record锁/Gap锁/Next-key锁/插入意 ...

  10. C# Socket异步实现消息发送--附带源码

    前言 看了一百遍,不如动手写一遍. Socket这块使用不是特别熟悉,之前实现是公司有对应源码改改能用. 但是不理解实现的过程和步骤,然后最近有时间自己写个demo实现看看,熟悉熟悉Socket. 网 ...