自定义配置属性 - 已添加条目

时间:2015-03-17 11:13:49

标签: app-config configurationproperty

我正在开发一个Windows服务,它在启动时从app.config读取信息,这样我们就可以在不重新部署服务的情况下更改内部线程配置。

我创建了一些自定义配置节和元素,如下所示(省略了实现):

public class MyConfigurationSection
{
    [ConfigurationProperty("threads")]
    [ConfigurationCollection(typeof(MyThreadCollection), AddItemName="addThread")>
    public MyThreadCollection threads { get; }
}

public class MyThreadCollection
{
    protected override void CreateNewElement();
    protected override object GetElementKey(ConfigurationElement element);
}

public class MyThreadElement
{
    [ConfigurationProperty("active", DefaultValue=true, IsRequired=false)>
    public bool active { get; set; }

    [ConfigurationProperty("batchSize", DefaultValue=10, IsRequired=false)>
    public int batchSize { get; set; }

    [ConfigurationProperty("system", IsRequired=true)>
    public string system { get; set; }

    [ConfigurationProperty("department", IsRequired=true)>
    public string department { get; set; }

    [ConfigurationProperty("connection", IsRequired=true)>
    public MyThreadConnectionElement connection { get; set; }
}

public class MyThreadConnectionElement
{
    [ConfigurationProperty("server", IsRequired=true)>
    public string server { get; set; }

    [ConfigurationProperty("database", IsRequired=true)>
    public string database { get; set; }

    [ConfigurationProperty("timeout", DefaultValue=15, IsRequired=false)>
    public int timeout { get; set; }
}

然后我将一些元素添加到app.config中,如下所示:

<configurationSection>
    <threads>
        <addThread
            active="True"
            batchSize="50"
            system="MySystem1"
            department="Department1">
            <connectionString
                server="MyServer"
                database="Database1" />
        </addThread>
        <addThread
            active="True"
            batchSize="30"
            system="MySystem2"
            department="Department2">
            <connectionString
                server="MyServer"
                database="Database2" />
        </addThread>
    </threads>
</configurationSection>

一切正常 - 读取配置,创建线程,并运行流程。

问题是,我希望这两个线程都具有相同的system名称/值 - 两者都应该是MySystem - 但是当我这样做并运行程序时,我得到一个The entry 'MySystem' has already been added.例外。

我认为可能是因为必须明确配置属性以允许重复,但我不知道如何找不到ConfigurationProperty类可能允许的属性除了IsKey之外,但从其描述来看,它似乎不是答案,并且尝试它并没有解决问题。我在这里走在正确的轨道上吗?

最初,system属性被命名为name,而我可能只将名为name的任何属性视为唯一标识符,因此我将其更改为system但是它并没有改变任何东西。

我尝试使用<clear />标记作为其他一些相似的帖子,但没有成功。

我是否需要在配置部分添加另一个层次结构 - 配置 - &gt;部门 - &gt;线程而不是配置 - &gt;线?我宁愿不接受这种做法。

感谢您提供的所有输入。

1 个答案:

答案 0 :(得分:4)

我实际上很久以前就找到了问题和解决方案,但忘记发布答案;谢谢@tote提醒我。

实现ConfigurationElementCollection类时,可以覆盖GetElementKey(ConfigurationElement)方法。没有立即意识到方法是什么我覆盖它并简单地返回system属性值,并且,因为多个配置元素具有相同的系统名称,从技术上讲它们具有相同的密钥,这就是发生错误的原因

我的解决方案是将systemdepartment值作为system.department返回,这会产生唯一键。

相关问题