我們正在使用Enterprise Library 5.0並希望使用日誌記錄應用程序塊將日誌/跟蹤消息寫入數據庫。執行web.config
文件中的所有配置就像冠軍一樣工作。企業庫5混合配置
但是,當應用程序啓動時,我們需要能夠指定記錄器動態使用的數據庫連接字符串。我們認爲我們可以通過使用Ent Lib 5.0 Fluent API以編程方式註冊連接字符串,然後將其與web.config
中的配置值合併,從而採用混合方法。這將允許我們能夠重新配置跟蹤消息的寫入方式/位置,而無需更改代碼。
這是我們曾嘗試:如果我檢查生成器對象在
<loggingConfiguration ...>
<listeners>
<add databaseInstanceName="TestDB" ... />
</listeners>
<formatters>...</formatters>
<categorySources>...</categorySources>
<specialSources>...</specialSources>
</loggingConfiguration>
:
var dynamicConnectionString = "..." // value determined elsewhere
var builder = new ConfigurationSourceBuilder();
builder.ConfigureData()
.ForDatabaseNamed("TestDB").ThatIs.ASqlDatabase()
.WithConnectionString(dynamicConnectionString);
var configSource = new SystemConfigurationSource();
// the line below throws an ArgumentException with the message
// 'Cannot add a ConfigurationSection with the same name that already exists'
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current = EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
在web.config
文件我們的測試項目,我們只有如下定義loggingConfiguration
節調試器,它只定義了1個部分:一個connectionStrings
部分,其中包含一個帶有通過代碼指定的值的單個connectionString
條目。 web.config
文件不包含包含connectionStrings
部分。具有諷刺意味的是,如果我使用「立即/觀察窗口」並檢查System.Configuration.ConfigurationManager.ConnectionStrings
,它會報告已經定義了1個連接...默認連接("data source=.\SQLExpress;Integrated Security=SSPI;AttacheDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true"
)。
如果我添加<connectionStrings><clear /></connectionStrings>
清除繼承的值,當我再次調試我仍然得到同樣的異常,因爲之前和 VS通知我,web.config
文件已被更新(如果我重新加載該文件,該<connectionStrings>
部分有已被刪除)。
我在這裏錯過了什麼!這不可能是那麼難!
很高興你發現這個博客很有用。 –