Search code examples
c#inversion-of-controlautofac

Using log4net with Autofac


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?

I am thinking of something like this

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

Thanks a lot


Solution

  • 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");
         }
    }
    

    In the application start (Global.asax.cs for Asp.net, MVC):

    // ...
    log4net.Config.XmlConfigurator.Configure();
    // ...
    iocBuilder.RegisterModule(new LoggingModule());
    iocBuilder.RegisterType<MyComponent>().AsSelf(); 
    
    // ...
    
    MyComponent c = iocContainer.Resolve<MyComponent>();
    c.Do(); 
    

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

    //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");