Core code
usingSystem;usingSystem.Data;usingSystem.Configuration;usingsystem.web;usingSystem.Web.Security;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.WebControls.WebParts;usingSystem.Web.UI.HtmlControls;namespacecommons{ Public classdefaultelement:configurationelement {[ConfigurationProperty ("Factory")] Public stringFactory {Get { return This["Factory"] as string; } Set { This["Factory"] =value; } } } Public classfactoryelement:configurationelement {[ConfigurationProperty ("name")] Public stringName {Get { return This["name"] as string; } Set { This["name"] =value; }} [ConfigurationProperty ("Assembly")] Public stringAssembly {Get { return This["Assembly"] as string; } Set { This["Assembly"] =value; }} [ConfigurationProperty ("class")] Public stringClass {Get { return This["class"] as string; } Set { This["class"] =value; } } } Public classfactoryelements:configurationelementcollection {protected Overrideconfigurationelement createnewelement () {return Newfactoryelement (); } protected Override ObjectGetelementkey (configurationelement element) {return((factoryelement) Element). Name; } PublicFactoryelement This[stringName] { Get { returnBaseget (name) asfactoryelement; } } } Public classdbfactorysection:configurationsection {[ConfigurationProperty ("default")] Publicdefaultelement defaultfactory {Get { return This["default"] asdefaultelement; } Set { This["default"] =value; }} [ConfigurationProperty ("Factorys")] Publicfactoryelements Factorys {Get { return This["Factorys"] asfactoryelements; } Set { This["Factorys"] =value; } } }}
View Code
Configuration file
<configsections> < Sectionname= "Dbfactory"type= "Commons.dbfactorysection"/> </configsections> <dbfactory> <defaultFactory= "SQL"></default> <Factorys> <Addname= "SQL"Assembly= "Hello.data"class= "Sqldbfactory" /> <Addname= "Oracle"Assembly= "Hello.data"class= "Oracledbfactory" /> <Addname= "SQLite"Assembly= "Hello.sqlite"class= "Sqlitedbfactory" /> <!--You can also add an infinite number of <ADD nodes - </Factorys> </dbfactory>
Used in code
Dbfactorysection DFS = configurationmanager.getsection ("dbfactory" as == fes["sql"= fes["sqlite"]
Asp. NET using ConfigurationSection to create a custom configuration section collection in Web. config