我想在我的应用程序中使用nlogger,将来可能需要更改日志记录系统.所以我想使用日志门面.
您是否知道对现有示例的任何建议如何编写这些示例?或者只是给我链接到这个领域的一些最佳实践.
如何从容器中拉出瞬态物体?我是否必须在容器中注册它们并注入需要类的构造函数?将所有内容注入构造函数中感觉不太好.也只是为了一个类,我不想创建一个TypedFactory并将工厂注入需要的类.
我想到的另一个想法是根据需要"新"起来.但我也在我的Logger所有类中注入一个组件(通过属性).因此,如果我新建它们,我将不得不手动实例化Logger这些类.如何继续为我的所有课程使用容器?
记录器注入:我的大多数类都Logger定义了属性,除非存在继承链(在这种情况下,只有基类具有此属性,并且所有派生类都使用该属性).当这些通过Windsor容器实例化时,它们会将我的实现ILogger注入其中.
//Install QueueMonitor as Singleton
Container.Register(Component.For<QueueMonitor>().LifestyleSingleton());
//Install DataProcessor as Trnsient
Container.Register(Component.For<DataProcessor>().LifestyleTransient());
Container.Register(Component.For<Data>().LifestyleScoped());
public class QueueMonitor
{
private dataProcessor;
public ILogger Logger { get; set; }
public void OnDataReceived(Data data)
{
//pull the dataProcessor from factory
dataProcessor.ProcessData(data);
}
}
public class DataProcessor
{
public ILogger Logger { get; set; }
public Record[] ProcessData(Data data)
{
//Data can have multiple Records
//Loop through the data and create new set …Run Code Online (Sandbox Code Playgroud) 这个问题与史蒂文的答案有关 - 这里.他提出了一个非常好的记录器包装器.我将在下面粘贴他的代码:
public interface ILogger
{
void Log(LogEntry entry);
}
public static class LoggerExtensions
{
public static void Log(this ILogger logger, string message)
{
logger.Log(new LogEntry(LoggingEventType.Information,
message, null));
}
public static void Log(this ILogger logger, Exception exception)
{
logger.Log(new LogEntry(LoggingEventType.Error,
exception.Message, exception));
}
// More methods here.
}
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是创建代理到log4net的实现的正确方法是什么?我应该只使用类型参数添加另一个Log扩展方法,然后在里面创建一个开关吗?如果使用不同的log4net方法LoggingEventType?
第二个问题,以后在代码中使用它的最佳方法是什么?
因为他写道:
(...)您可以轻松创建ILogger实现(...)并配置您的DI容器以将其注入到在其构造函数中具有ILogger的类中.
这是否意味着每个会记录的类(基本上都是每个)都应该ILogger在它的构造函数中?