我正在尝试使用Fluent API编写没有配置文件的日志。
这是我的代码:
var builder = new ConfigurationSourceBuilder();
builder.ConfigureData()
.ForDatabaseNamed("Logging")
.ThatIs.ASqlDatabase()
.WithConnectionString(ConnectionString)
.AsDefault();
var configSource = new DictionaryConfigurationSource();
builder.UpdateConfigurationWithReplace(configSource);
var logger = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
logger.Write("Test", "General");
当我运行它时,它只是说
尝试获取LogWriter类型的实例时出现激活错误,键“”
我在配置中做错了什么?
答案 0 :(得分:2)
缺少两件事:
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配置日志记录,请参阅Using the Fluent Configuration 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");