我们正在使用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>
部分有已被删除)。
我在这里错过了什么!这不可能是那么难!
很高兴你发现这个博客很有用。 –