Friday, November 13, 2009

The Simplest Possible Ninject log4net Binding

I’ve been using Ninject more and more. I also use log4net for logging. But how to do I get my log4net peanut butter into my Ninject chocolate? Like this:

Bind<ILog>().ToMethod(x => LogManager.GetLogger(x.Request.ParentContext.Plan.Type)); 

As far as I can tell, this is the simplest possible way to get Ninject to build an ILog object for dependency injection. NOTE! This is only valid for dependency injection! If you just call:


kernel.Get<ILog>();

You will be less than satisfied with the results… However, this works brilliantly:


public class Notifier : INotifier
{
private readonly ILog _log;

public Notifier(ILog log)
{
_log = log;
}
}

No wrappers, static classes or helper objects! If I ever meet Nate Kohari, I’m going to give him a big ol' hug. I may even tear up a little bit…