[英]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
名稱/值 - 兩者都應該是MySystem
- 但是當我這樣做並運行程序時,我得到了一個The entry 'MySystem' has already been added.
例外。
我想這可能是因為必須顯式配置屬性以允許重復,但我不知道如何和我找不到可能允許的屬性的ConfigurationProperty
類,除了IsKey
,但是從它的描述中似乎不是答案,嘗試它並沒有解決問題。 我在這里走在正確的軌道上嗎?
最初, system
屬性被命名為name
,我可能只是將名為name
任何屬性視為唯一標識符,因此我將其更改為system
但它沒有更改任何內容。
我嘗試了<clear />
標簽作為其他一些類似的帖子,沒有成功。
我是否需要在配置部分添加另一個層次結構 - 配置 - >部門 - >線程而不是配置 - >線程? 我寧願不采取這種方法。
感謝任何和所有的輸入。
我實際上很久以前就找到了問題和解決方案,但忘記發布答案; 謝謝@tote提醒我。
實現ConfigurationElementCollection
類時,可以重寫GetElementKey(ConfigurationElement)
方法。 沒有立即意識到方法是什么我覆蓋它並簡單地返回system
屬性值,並且,由於多個配置元素具有相同的系統名稱,從技術上講它們具有相同的密鑰,這就是錯誤發生的原因。
對我來說,解決方案是將system
和department
值作為system.department
返回,從而產生唯一鍵。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.