解决方案:只是添加解决方案: sectionGroups似乎没有属性。正确的方法似乎是以ConfigurationSection作为父级,ConfigurationElement作为每个子级。还有用于集合的ConfigurationElementCollection。.net框架中的一个例子:<roleManager>是一个节,<providers>是一个ElementCollection。I 写了我的解决方案。
原始问题:--我的web.config中有一个自定义sectionGroup:
<sectionGroup name="myApp" type="MyApp.MyAppSectionGroup">
<section name="localeSettings"
type="MyApp.MyAppLocaleSettingsSection"/>
</sectionGroup>sectionGroup本身应该有一个属性:
<myApp defaultModule="MyApp.MyAppTestNinjectModule">
<localeSettings longDateFormat="MM/dd/yyyy HH:mm:ss" />
</myApp>我在访问该属性(defaultModule)时遇到了问题。使用ConfigurationManager.GetSection("myApp/localeSettings")并将其转换为继承自ConfigurationSection的类非常容易。
但是我似乎很难访问sectionGroup,因为ConfigurationManager.GetSection("myApp")返回null。我尝试过ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None).SectionGroups["myApp"],但这并不能实现允许我访问defaultModule的索引器。
我是不是误会了什么?sectionGroups真的只是没有自己的设置的容器吗?我可以在没有sectionGroup的情况下嵌套部分吗?OpenExeConfiguration是否适合于.net应用程序(使用web.config),还是仅适用于app.config?
编辑:感谢关于WebConfigurationManager而不是ConfigurationManager的提示。这并不能解决我的主要问题,但至少有更合理的OpenXXX方法。
目前,这是两个班。LocaleSettings运行得非常好,只是SectionHandler不允许我访问"defaultModule“属性。
public class MyAppSectionGroup: ConfigurationSectionGroup
{
[ConfigurationProperty("localeSettings")]
public MyAppLocaleSettingsSection LocaleSettings
{
get
{
return Sections["localeSettings"] as MyAppLocaleSettingsSection;
}
}
}
public class MyAppLocaleSettingsSection: ConfigurationSection
{
[ConfigurationProperty("longDateFormat", DefaultValue = "yyyy-MM-dd HH:mm")]
public string LongDateFormat
{
get
{
return this["longDateFormat"] as string;
}
}
}发布于 2009-12-28 09:06:55
几乎你想做的一切都应该是可能的,而且应该是合法的--我想你一定是错过了一些小的东西。我唯一不确定的是,节组是否可以有它们自己的属性--它们可能被设计为只是作为节的容器,而这些部分中有实际的配置数据.
对于访问web.config,您还应该尝试使用WebConfigurationManager而不是“直”ConfigurationManager (用于app.config文件)。
你能给我们看看你的MyApp.MyAppSectionHandler和MyApp.MyAppLocaleSettingsConfigurationSection的代码吗?
你看过乔恩·里斯塔关于.NET 2.0在CodeProject上的配置的三部分系列吗?这是一个很好的介绍如何使用和扩展.NET配置系统-强烈推荐,也是最有用的!
如果您正在处理自定义配置部分,我还建议您查看配置部分设计器,这是一个visually插件,允许您可视化地定义配置节组和配置节,以及这些部分中的属性及其数据类型--非常好的时间节省器和教育工具!
更多的挖掘表明:
[ConfigurationProperty],但是这些属性没有自动的“后备存储”,而且我也看不到从配置文件中连接到XML加载的任何方式--所以我认为节组实际上只是容器。Marc
https://stackoverflow.com/questions/1968592
复制相似问题