【发布时间】:2013-01-29 00:10:25
【问题描述】:
我想分发一个带有ConfigurationSection 的DLL,如下所示:
public class StandardConfiguration : ConfigurationSection
{
public static StandardConfiguration GetInstance()
{
return (StandardConfiguration)ConfigurationManager.GetSection("customConfigSection");
}
[ConfigurationProperty("childConfig")]
public StandardChildConfig ChildConfig
{
get { return (StandardChildConfig)this["childConfig"]; }
set { this["childConfig"] = value; }
}
}
public class StandardChildConfig : ConfigurationElement
{
[ConfigurationProperty("p1")]
public string P1
{
get { return (string)this["p1"]; }
set { this["p1"] = value; }
}
}
我想让ConfigurationSection 及其子ConfigElement 可继承。这可以使用类型参数来完成,如下所示:
public class StandardConfiguration<TChildConfig> : ConfigurationSection
where TChildConfig : StandardChildConfig
{
[ConfigurationProperty("childConfig")]
public TChildConfig ChildConfig
{
get { return (TChildConfig)this["childConfig"]; }
set { this["childConfig"] = value; }
}
}
public class StandardChildConfig : ConfigurationElement
{
[ConfigurationProperty("p1")]
public string P1
{
get { return (string)this["p1"]; }
set { this["p1"] = value; }
}
}
但是,我认为这会阻止我从我的 DLL 中的其他类引用静态 Instance,因为我不知道子 ConfigurationElement 的最终类型。
欢迎任何关于如何更干净地实现这一点的想法或建议。
谢谢。
编辑
假设应用程序的配置中有一个<customConfigSection>,我可以在第一个场景中使用StandardConfiguration.GetInstance().ChildConfig.P1 来访问P1 的值。在第二种情况下,我将如何访问相同的值?我将如何实现GetInstance()?
编辑 2
以下是“零编码”场景:
<?xml version="1.0"?>
<configuration>
<configSections>
<section
name="customConfig"
type="WebsiteTemplate.Config.StandardConfigruation, WebsiteTemplate"
/>
</configSections>
<customConfig baseProp1="a">
<childConfig baseProp2="b" />
</customConfig>
</configuration>
这是扩展配置的场景:
<?xml version="1.0"?>
<configuration>
<configSections>
<section
name="customConfig"
type="WebsiteTemplate.Extended.Config.ExtendedConfigruation, WebsiteTemplate.Extended"
/>
</configSections>
<customConfig baseProp1="a" extendedProp1="c">
<childConfig baseProp2="b" extendedProp2="d" />
</customConfig>
</configuration>
【问题讨论】:
-
而
Instance的类型不能是ConfigurationElement?我不清楚你在问什么...... -
@Peter Ritchie - 我添加了一个我正在尝试做的示例。让我知道这是否有意义。谢谢。
-
只需使用我的库即可github.com/aloneguid/config
标签: c# .net oop design-patterns