【发布时间】:2015-11-13 21:33:39
【问题描述】:
我们正在使用 Enterprise Library 5.0,并希望使用 Logging 应用程序块将日志/跟踪消息写入数据库。在web.config 文件中进行所有配置就像一个冠军。
但是,当应用程序启动时,我们需要能够指定记录器动态使用的数据库连接字符串。我们认为我们可以采用混合方法,使用 Ent Lib 5.0 Fluent API 以编程方式注册连接字符串,然后将其与来自web.config 的配置值合并。这将使我们能够重新配置跟踪消息的写入方式/位置,而无需更改代码。
这是我们尝试过的:
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 部分,如下所示:
<loggingConfiguration ...>
<listeners>
<add databaseInstanceName="TestDB" ... />
</listeners>
<formatters>...</formatters>
<categorySources>...</categorySources>
<specialSources>...</specialSources>
</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> 部分已被删除)。
我在这里错过了什么!这不会那么难!
【问题讨论】:
标签: c# asp.net logging enterprise-library enterprise-library-5