How can I resolve the correct logger type using AutoFac?

Viewed 8565

I'm updating a legacy project that uses AutoFac and I want to use NLog with Simple Logging Facade (SLF)

I have used this in the past with Ninject and it's really easy to setup, I just have to do something like:

kernel.Bind<ILogger>().ToMethod(x => LoggerFactory.GetLogger(x.Request.Target.Member.ReflectedType));

The output would be something like:

NLogNinjectSlf.Services.MyService 2013-12-30 15:21:10.5782 DEBUG Log from injected Logger

Piece of cake

But now I have to use AutoFac and I don't know how to get the Target type that needs the logger

For example if I have the following interface/class:

public interface IMyService
{
    void DoSomething();
}

public class MyService : IMyService
{
    private readonly ILogger _logger;

    public MyService(ILogger logger)
    {
        _logger = logger;
    }

    public void DoSomething()
    {
        _logger.Debug("Log from injected Logger");
    }
}

I want to be able to get the type of MyService class to use it as the name of my logger

In AutoFac this is what I have tried so far:

var containerBuilder = new ContainerBuilder();

containerBuilder.RegisterType<MyService>().As<IMyService>();

containerBuilder.Register(x =>
{
    // TODO: Get the correct type
    return LoggerFactory.GetLogger(x.GetType());
}).As<ILogger>();

BTW: I'm using NLog behind the SLF4Net not really needed to solve the main issue though...

2 Answers
Related