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

Custom configuration properties - Entry has already been added

我正在开发一个 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 name/value -- 两者都应该是 MySystem -- 但是当我这样做时 运行 程序,我得到一个 The entry 'MySystem' has already been added. 异常。

我想这可能是因为 属性 必须明确配置为允许重复,但我不知道如何,我找不到 [=15 的 属性 =] class 可能允许这样做,但 IsKey 除外,但从它的描述来看,它似乎不是答案,并且尝试它并没有解决问题。我走在正确的轨道上吗?

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

我尝试了 <clear /> 标签,正如其他一些类似帖子所建议的那样,但没有成功。

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

感谢您的所有意见。

我其实很久以前就找到了问题和解决方案,但是忘了 post 答案;谢谢@tote 提醒我。

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

我的解决方案是 return systemdepartment 值作为 system.department,这导致唯一键。