缺少两件事:
- 您忘记使用该
EnterpriseLibraryContainer.CreateDefaultContainer
方法使用配置更新容器
- 您正在配置数据访问,但正在尝试使用日志记录块
以下是使用配置信息创建容器的方法:
var builder = new ConfigurationSourceBuilder();
builder.ConfigureData()
.ForDatabaseNamed("Logging")
.ThatIs.ASqlDatabase()
.WithConnectionString(ConnectionString)
.AsDefault();
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
要使用 Fluent API 配置日志记录,请参阅使用 Fluent 配置 API。
那篇文章的例子是:
var builder = new ConfigurationSourceBuilder();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.LogToCategoryNamed("Security")
.SendTo.FlatFile("Security Log File")
.FormatWith(new FormatterBuilder()
.TextFormatterNamed("Text Formatter")
.UsingTemplate("Timestamp: {timestamp}...{newline})}"))
.ToFile("security.log")
.SendTo.EventLog("Formatted EventLog TraceListener")
.FormatWithSharedFormatter("Text Formatter")
.ToLog("Application")
.LogToCategoryNamed("General")
.WithOptions.SetAsDefaultCategory()
.SendTo.SharedListenerNamed("Formatted EventLog TraceListener");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
如果您希望将两个日志记录块配置为使用数据访问块写入数据库,您也可以使用流利的界面来执行此操作:
var builder = new ConfigurationSourceBuilder();
builder.ConfigureData()
.ForDatabaseNamed("Logging")
.ThatIs.ASqlDatabase()
.WithConnectionString(@"data source=.\SQLEXPRESS;Integrated Security=SSPI;Database=Logging")
.AsDefault();
builder.ConfigureLogging()
.WithOptions
.DoNotRevertImpersonation()
.LogToCategoryNamed("General")
.WithOptions.SetAsDefaultCategory()
.SendTo.Database("Database Trace Listener")
.WithAddCategoryStoredProcedure("AddCategory")
.UseDatabase("Logging")
.Filter(System.Diagnostics.SourceLevels.All)
.WithWriteLogStoredProcedure("WriteLog");
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
EnterpriseLibraryContainer.Current
= EnterpriseLibraryContainer.CreateDefaultContainer(configSource);
var logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
logger.Write(logEntry);
Logger.Write("Test", "General");