<configSections>
<section name="dbFactory"
type="DbFactory.Configuration.DbFactorySection, DbFactory.Configuration" />
</configSections>
<dbFactory>
<default factory="sql" />
<factorys>
<add name="sql" assembly="Hello.Data" class="SqlDbFactory" />
<add name="oracle" assembly="Hello.Data" class="OracleDbFactory" />
</factorys>
</dbFactory>
public class DefaultElement : ConfigurationElement
{
[ConfigurationProperty("factory", IsRequired = true)]
public string Factory
{
get => (string)this["factory"];
set => this["factory"] = value;
}
}
public class FactoryElement : ConfigurationElement
{
[ConfigurationProperty("name", IsRequired = true, IsKey = true)]
public string Name
{
get => (string)this["name"];
set => this["name"] = value;
}
[ConfigurationProperty("assembly", IsRequired = true)]
public string Assembly
{
get => (string)this["assembly"];
set => this["assembly"] = value;
}
[ConfigurationProperty("class", IsRequired = true)]
public string Class
{
get => (string)this["class"];
set => this["class"] = value;
}
}
public class FactoryElements : ConfigurationElementCollection
{
protected override ConfigurationElement CreateNewElement()
=> new FactoryElement();
protected override object GetElementKey(ConfigurationElement element)
=> ((FactoryElement)element).Name;
public FactoryElement this[string name]
=> BaseGet(name) as FactoryElement;
}
public class DbFactorySection : ConfigurationSection
{
[ConfigurationProperty("default")]
public DefaultElement DefaultFactory
{
get => (DefaultElement)this["default"];
set => this["default"] = value;
}
[ConfigurationProperty("factorys")]
public FactoryElements Factorys
{
get => (FactoryElements)this["factorys"];
set => this["factorys"] = value;
}
}
var section = ConfigurationManager.GetSection("dbFactory") as DbFactorySection;
if (section != null)
{
string defaultFactory = section.DefaultFactory.Factory;
foreach (FactoryElement fe in section.Factorys)
{
Console.WriteLine($"{fe.Name}: {fe.Assembly}, {fe.Class}");
}
}
ConfigurationElement // 單一元素基類
→ ConfigurationElementCollection // 集合元素基類 (抽象,需實現 CreateNewElement/GetElementKey)
ConfigurationSection // 配置節基類 (對應 XML 根節點)
ConfigurationManager.GetSection // 統一讀取入口
PostDeserialize() 執行跨屬性驗證[ConfigurationProperty("name", DefaultValue="sql")]configSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider")<section configSource="dbFactory.config" />section.SectionInformation.ForceSave = true; config.Save().NET 配置系統提供完整的「聲明式 XML + 強類型物件」映射機制。掌握 ConfigurationElement/Collection/Section 三層體系,即可構建類型安全、IntelliSense 友好、支援驗證加密的企業級配置模型,遠優於手工 XML 解析。