3

我正在开发一个 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,但从它的描述中它没有' t 似乎是答案,尝试它并没有解决问题。我在正确的轨道上吗?

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

<clear />我按照其他一些类似帖子的建议尝试了该标签,但没有成功。

我是否需要向配置部分添加另一个层次结构--配置->部门->线程而不是配置->线程?我宁愿不采用这种方法。

感谢您的任何和所有输入。

4

1 回答 1

4

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

在实现ConfigurationElementCollection类时,GetElementKey(ConfigurationElement)可以重写该方法。在没有立即意识到该方法的用途的情况下,我覆盖了它并简单地返回了system属性值,并且由于多个配置元素具有相同的系统名称,因此从技术上讲它们具有相同的键,这就是发生错误的原因。

我的解决方案是返回导致唯一键system的值和department值。system.department

于 2015-05-04T11:22:56.673 回答