ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合相关的知识,希望对你有一定的参考价值。
核心代码
using System; 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"]
以上是关于ASP.NET使用ConfigurationSection在Web.Config创建自定义配置节集合的主要内容,如果未能解决你的问题,请参考以下文章
[译] ASP.NET 生命周期 – ASP.NET 请求生命周期