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...
Thanks nemesv that helped me a lot
This is the code that I ended up using
BTW. You can remove the code that inject properties if you wish, and then just use DI in all your classes to inject the
ILogger
that would increase the performanceThen register the module:
Seems using Autofac 4.3.0 you can simply use OnComponentPreparing() callback without using special properties injection techniques. Both ctor() and properties' values will be injected:
Also I found some nice trick which might be used for properties injection only when you need to control logger lifetime.
where NLogLogger itself is