我正在尝试为 .NET4 应用程序编写一个非常简单的自定义配置部分。我的目标是这样的:
<configuration>
<configSections>
<section name="myServices" type="My.ConfigSection, My.Assembly" />
</configSections>
<myServices>
<add name="First" />
<add name="Second" />
</myServices>
</configuration>
但是,ConfigurationErrorsException
当我调用ConfigurationManager.GetSection("myServices")
. 我已经盯着它看了一段时间,但还没有弄清楚我做错了什么。下面是我的代码。它是三个类ConfigSection
:MyServiceSettingsCollection
和MyServiceSettings
。
首先是代表整个配置部分的类。它有一个无名的默认类型集合MyServiceSettingsCollection
。该IsDefaultCollection
属性应该允许我从根元素直接“添加”到我的集合中。
public sealed class ConfigSection : ConfigurationSection
{
private static readonly ConfigurationProperty _propMyServices;
private static readonly ConfigurationPropertyCollection _properties;
public static ConfigSection Instance { get { return _instance; } }
static ConfigSection()
{
_propMyServices = new ConfigurationProperty(
null, typeof(MyServiceSettingsCollection), null,
ConfigurationPropertyOptions.IsDefaultCollection);
_properties = new ConfigurationPropertyCollection { _propMyServices };
}
[ConfigurationProperty("", IsDefaultCollection = true)]
public MyServiceSettingsCollection MyServices
{
get { return (MyServiceSettingsCollection) base[_propMyServices]; }
set { base[_propMyServices] = value; }
}
protected override ConfigurationPropertyCollection Properties
{ get { return _properties; } }
}
接下来是集合类本身。它是类型AddRemoveClearMap
。
[ConfigurationCollection(typeof(MyServiceSettings),
CollectionType = ConfigurationElementCollectionType.AddRemoveClearMap)]
public sealed class MyServiceSettingsCollection : ConfigurationElementCollection
{
public MyServiceSettings this[int index]
{
get { return (MyServiceSettings) BaseGet(index); }
set
{
if (BaseGet(index) != null) { BaseRemoveAt(index); }
BaseAdd(index, value);
}
}
public new MyServiceSettings this[string key]
{
get { return (MyServiceSettings) BaseGet(key); }
}
protected override ConfigurationElement CreateNewElement()
{
return new MyServiceSettings();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((MyServiceSettings) element).Key;
}
}
最后是集合中元素的类。目前,这个类只有一个属性,但以后会有更多(这使我无法使用NameValueSectionHandler
)。
public class MyServiceSettings : ConfigurationElement
{
private static readonly ConfigurationProperty _propName;
private static readonly ConfigurationPropertyCollection properties;
static MyServiceSettings()
{
_propName = new ConfigurationProperty("name", typeof(string), null, null,
new StringValidator(1),
ConfigurationPropertyOptions.IsRequired |
ConfigurationPropertyOptions.IsKey);
properties = new ConfigurationPropertyCollection { _propName };
}
[ConfigurationProperty("name", DefaultValue = "",
Options = ConfigurationPropertyOptions.IsRequired |
ConfigurationPropertyOptions.IsKey)]
public string Name
{
get { return (string) base[_propKey]; }
set { base[_propKey] = value; }
}
protected override ConfigurationPropertyCollection Properties
{ get { return properties; } }
}