本文介绍了将log4net与Autofac一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将log4net与Autofac一起使用.我已将此代码粘贴 http://autofac.readthedocs.org/en/latest/examples/log4net.html ,并从Program.cs/Main()中执行

I am trying to use log4net with Autofac.I've pasted this code http://autofac.readthedocs.org/en/latest/examples/log4net.html ,and from Program.cs/Main() I am doing

var iocBuilder = new ContainerBuilder();
iocBuilder.RegisterModule(new LoggingModule());
var iocContainer = iocBuilder.Build();

现在,我想立即尝试此操作(在下一行中),在日志文件中写一条简单的线.我该怎么办?

now I would like to try this out immediately (in the next line),writing a simple line to the log file. How should I do it?

我在想这样的事情

var ls = iocContainer.Resolve<LoggingModule>();
ls.Info("the logging is working");

非常感谢

推荐答案

要获取ILog,log4net需要知道使用记录器的类(LogManager.GetLogger(...)).因此,没有父类就无法解析ILog.您必须将ILog注入组件内部.

To obtain a ILog, log4net need to know the class that use the logger (LogManager.GetLogger(...)). So, you can't resolve a ILog without a parent class. You have to inject the ILog inside a component.

public class MyComponent
{
     public MyComponent(ILog logger)
     {
          this._logger = logger;
     }

     private readonly ILog _logger;

     public void Do()
     {
          this._logger.Info("Log4net OK");
     }
}

在应用程序中启动(对于Asp.net,MVC,为Global.asax.cs):

// ...
log4net.Config.XmlConfigurator.Configure();
// ...
iocBuilder.RegisterModule(new LoggingModule());
iocBuilder.RegisterType<MyComponent>().AsSelf();

// ...

MyComponent c = iocContainer.Resolve<MyComponent>();
c.Do();

另一种解决方案是为Object注册一个ILog并解析ILog.在这种情况下,不需要模块.

Another solution would be to register an ILog for Object and resolve ILog. In this case, the module is not required.

//在"DI容器"构建器中:

//In the DI container builder:

log4net.Config.XmlConfigurator.Configure();
/// ...
ContainerBuilder cb = new ContainerBuilder()
cb.Register(c => LogManager.GetLogger(typeof(Object))).As<ILog>();
IContainer container = cb.Build();

//在需要使用记录器的函数中:

//In the function where we need to ue the logger:

ILog logger = container.Resolve<ILog>();
logger.Info("log4net OK");

这篇关于将log4net与Autofac一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 03:09