核心代码
using System;View Code
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace Commons
{
public class DefaultElement : ConfigurationElement
{
[ConfigurationProperty("factory")]
public string Factory
{
get
{
return this["factory"] as string;
}
set
{
this["factory"] = value;
}
}
}
public class FactoryElement : ConfigurationElement
{
[ConfigurationProperty("name")]
public string Name
{
get
{
return this["name"] as string;
}
set
{
this["name"] = value;
}
}
[ConfigurationProperty("assembly")]
public string Assembly
{
get
{
return this["assembly"] as string;
}
set
{
this["assembly"] = value;
}
}
[ConfigurationProperty("class")]
public string Class
{
get
{
return this["class"] as string;
}
set
{
this["class"] = value;
}
}
}
public class FactoryElements : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
{
return new FactoryElement();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((FactoryElement)element).Name;
}
public FactoryElement this[string name]
{
get
{
return BaseGet(name) as FactoryElement;
}
}
}
public class DbFactorySection : ConfigurationSection
{
[ConfigurationProperty("default")]
public DefaultElement DefaultFactory
{
get
{
return this["default"] as DefaultElement;
}
set
{
this["default"] = value;
}
}
[ConfigurationProperty("factorys")]
public FactoryElements Factorys
{
get
{
return this["factorys"] as FactoryElements;
}
set
{
this["factorys"] = value;
}
}
}
}
配置文件
<configSections>
<section name="dbFactory" type="Commons.DbFactorySection"/>
</configSections>
<dbFactory >
<default factory="sql"></default>
<factorys>
<add name="sql" assembly="Hello.Data" class="SqlDbFactory" />
<add name="oracle" assembly="Hello.Data" class="OracleDbFactory" />
<add name="sqlite" assembly="Hello.sqlite" class="SqliteDbFactory" />
<!--还可以添加无数个<add 节点-->
</factorys>
</dbFactory>
代码中使用
DbFactorySection dfs = ConfigurationManager.GetSection("dbFactory") as DbFactorySection;
FactoryElements fes = dfs.Factorys;
FactoryElement feSql = fes["sql"];
FactoryElement feSqlite = fes["sqlite"]