【发布时间】:2011-04-25 12:29:56
【问题描述】:
我正在尝试在项目中实现自定义配置部分,并且一直遇到我不理解的异常。我希望有人可以在这里填补空白。
我有App.config,看起来像这样:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="ServicesSection" type="RT.Core.Config.ServicesConfigurationSectionHandler, RT.Core"/>
</configSections>
<ServicesSection type="RT.Core.Config.ServicesSection, RT.Core">
<Services>
<AddService Port="6996" ReportType="File" />
<AddService Port="7001" ReportType="Other" />
</Services>
</ServicesSection>
</configuration>
我有一个 ServiceConfig 元素定义如下:
public class ServiceConfig : ConfigurationElement
{
public ServiceConfig() {}
public ServiceConfig(int port, string reportType)
{
Port = port;
ReportType = reportType;
}
[ConfigurationProperty("Port", DefaultValue = 0, IsRequired = true, IsKey = true)]
public int Port
{
get { return (int) this["Port"]; }
set { this["Port"] = value; }
}
[ConfigurationProperty("ReportType", DefaultValue = "File", IsRequired = true, IsKey = false)]
public string ReportType
{
get { return (string) this["ReportType"]; }
set { this["ReportType"] = value; }
}
}
我有一个 ServiceCollection 定义如下:
public class ServiceCollection : ConfigurationElementCollection
{
public ServiceCollection()
{
Console.WriteLine("ServiceCollection Constructor");
}
public ServiceConfig this[int index]
{
get { return (ServiceConfig)BaseGet(index); }
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
public void Add(ServiceConfig serviceConfig)
{
BaseAdd(serviceConfig);
}
public void Clear()
{
BaseClear();
}
protected override ConfigurationElement CreateNewElement()
{
return new ServiceConfig();
}
protected override object GetElementKey(ConfigurationElement element)
{
return ((ServiceConfig) element).Port;
}
public void Remove(ServiceConfig serviceConfig)
{
BaseRemove(serviceConfig.Port);
}
public void RemoveAt(int index)
{
BaseRemoveAt(index);
}
public void Remove(string name)
{
BaseRemove(name);
}
}
我缺少的部分是为处理程序做什么。最初,我尝试实现一个IConfigurationSectionHandler,但发现了两件事:
- 没用
- 已弃用。
我现在完全不知道该怎么做,所以我可以从配置中读取我的数据。请帮忙!
【问题讨论】:
-
我无法正常工作。我很想看到 RT.Core.Config.ServicesSection。尽管也使用了已接受答案中的代码,但我还是得到了 Unrecognized element 'AddService'。
-
我一开始也错过了这个 - 这部分:[ConfigurationCollection(typeof(ServiceCollection), AddItemName = "add", ClearItemsName = "clear", RemoveItemName = "remove")] AddItemName 必须匹配因此,如果您将“add”更改为“addService”,它将起作用
标签: c# configuration app-config configuration-files