當我們開發系統的時候要把一部分設置提取到外部的時候,那麼就要用到.NET的配置文件了。比如我的框架中使用哪個IOC容器需要可以靈活的選擇,那我就需要把IOC容器的設置提取到配置文件中去配置。實現有幾種方法。
這個是最簡單的可以設置和讀取的用戶設置
簡單實用但是不夠優雅。
public class AgileFRConfigurationHandler: IConfigurationSectionHandler
{
public object Create(object parent, object configContext, XmlNode section)
{
var node =section.ChildNodes[0];
if (node.Name != "objectContainer")
throw new ConfigurationErrorsException("不可識別的配置項", node);
var config = new ObjectContainerElement();
foreach (XmlAttribute attr in node.Attributes)
{
switch (attr.Name)
{
case "provider":
config. Provider = attr.Value;
break;
case "iocModule":
config .IocModule = attr.Value;
break;
default:
throw new ConfigurationErrorsException("不可識別的配置屬性", attr);
}
}
}
return config;
}//使用
var config = ConfigurationManager.GetSection("agileFRConfiguration") as ObjectContainerElement;
這個方法看上去就略屌了,不過就是太麻煩了。
繼承ConfigurationSection類,配合ConfigurationProperty特性來實現
public class ObjectContainerElement : ConfigurationElement
{
[ConfigurationProperty("provider", IsRequired = true)]
public string Provider
{
get
{
return (string)this["provider"];
}
set
{
this["provider"] = (object)value;
}
}
[ConfigurationProperty("iocModule", IsRequired = false)]
public string IocModule
{
get
{
return (string)this["iocModule"];
}
set
{
this["iocModule"] = (object)value;
}
}
}
/// <summary>
/// 配置處理類
/// </summary>
public class AgileFRConfigurationHandler : ConfigurationSection
{
[ConfigurationProperty("objectContainer", IsRequired = true)]
public ObjectContainerElement ObjectContainer
{
get
{
return (ObjectContainerElement)this["objectContainer"];
}
set
{
this["objectContainer"] = (object)value;
}
}
}//使用
var configurationHandler = (AgileFRConfigurationHandler)ConfigurationManager.GetSection("agileFRConfiguration");
var objectContainer=configurationHandler.ObjectContainer;這個方法簡單優雅,我喜歡。
這個方法我不太喜歡,它會自己生成配置文件對應的Class。不說了。