简单而自定义的配置文件
只需很少的代码,你就能拥有一个可定制且可扩展的配置文件。
引言
我一直喜欢简洁的理念。配置文件旨在改变程序行为,而无需修改代码。修改的代码越少越好。
为了达到这个简单的目标,仅仅使用一个XmlNode
来表示配置节就足够了。任何配置扩展或模式更改都不会影响这部分配置代码。当然,你可以选择ConfigSection
等方式,但那样会破坏简洁性,而且对于支持人员来说,代码更改并不容易接受。
为了提高性能,如果你需要频繁访问配置值,可以对以下内容进行一些优化。
配置
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="HSONG" type="com.hsong.Configuration.MyConfigHandler, tcustconfig"
allowDefinition="Everywhere"
allowExeDefinition="MachineToApplication"
restartOnExternalChanges="true" />
</configSections>
<!-- CHANGE YOUR CONSTOM SECTION AS YOU WISH -->
<HSONG>
<APPSETA>JUNKA</APPSETA>
<APPSETB>
<ANOTHERX>JUNKB</ANOTHERX>
</APPSETB>
</HSONG>
<!--END OF YOUR CONSTOM SECTION AS YOU WISH -->
</configuration>
这里有一个简单的解释:上面的<section>
告诉我们,可以加载一个关于HSONG
自定义节的类。该类是com.hsong.Configuration.MyConfigHandler
,程序集是tcustconfig
。
接下来,就是定义处理配置的类(com.hsong.Configuration.MyConfigHandler
)。
IConfigurationHandler 和代码示例
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
namespace com.hsong.Configuration
{
public class MyProjConfig
{
private static MyProjConfig theConfig;
private static XmlNode cfgNode = null;
internal static XmlNode ConfigXmlNode
{
set
{
if (cfgNode != null) return;
cfgNode = value;
theConfig = new MyProjConfig();
ConfigurationManager.GetSection("HSONG");
}
}
public static MyProjConfig GetConfig()
{
return theConfig;
}
public int GetCount(string xmlpath)
{
return cfgNode.SelectNodes(xmlpath).Count;
}
public string GetValue(string xmlpath, params int[] index)
{
System.Xml.XmlNodeList ndlist = cfgNode.SelectNodes(xmlpath);
int nnodes = ndlist.Count;
if (nnodes == 0) return null;
int nindex = (index == null || index.Length == 0) ? 0 : index[0];
System.Xml.XmlNode nx = ndlist.Item(nindex);
return nx.InnerXml;
}
}
public class MyConfigHandler : IConfigurationSectionHandler
{
public object Create(object parent, object context, XmlNode node)
{
MyProjConfig.ConfigXmlNode = node;
return MyProjConfig.GetConfig(); // cause it to load config from node.
}
}
}
// example use, obtain config value by the xpath...
namespace tcustconfig
{
class Program
{ // example use
static void Main(string[] args)
{
com.hsong.Configuration.MyProjConfig cfg=
(com.hsong.Configuration.MyProjConfig)
System.Configuration.ConfigurationManager.GetSection("HSONG");
string va = cfg.GetValue("APPSETA"); // WHATEVER XPATH YOU MATCH YOUR CONFIG..
string vb = cfg.GetValue("APPSETB/ANOTHERX");
string vc = cfg.GetValue("APPSETB");
//
}
}
}
结论
保持简单易用,方便其他开发人员一起工作。当你的团队有很多代码需要担心时,你希望他们专注于业务,而不是玩弄技巧。
历史
- 2006年4月10日:初始发布