Reputation: 10792
I'm trying to add dependency injection to Nlog using Ninject for unit testing purposes, but I cannot get it to work. :( I'm getting a NullReferenceException when calling GetCurrentClassLogger(). I'm new to both Nlog and Ninject, this is actually my first time using them.
Main
using NLog;
using Ninject;
using Ninject.Extensions.Logging;
using Ninject.Extensions.Logging.NLog2;
public class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel(new NLogModule());
var logFactory = kernel.Get<ILoggerFactory>();
var run = new MyClass(logFactory);
}
}
MyClass
using Ninject.Extensions.Logging;
public class MyClass
{
private readonly ILogger _log;
public MyClass(ILoggerFactory logFactory)
{
_log = logFactory.GetCurrentClassLogger();
}
public void DoWork()
{
_log.Info("Doing work!");
}
}
Hope someone can help me.
Upvotes: 1
Views: 1883
Reputation: 10792
This is how I ended up solving it. Thanks to Claus Jørgensen helping me out on IRC :)
Apparently there is some auto binding in place when using the NLog extension so doing new StandardKernel(new NLogModule());
would result in the module to be loaded twice.
Main
using Ninject;
public class Program
{
static void Main(string[] args)
{
var kernel = new StandardKernel();
var run = kernel.Get<MyClass>();
run.DoWork();
}
}
Hope this helps someone.
Upvotes: 1