views:

326

answers:

2

I'm using Ninject for DI in my asp.net application, so my Global class inherits from NinjectHttpApplication.

In my CreateKernel(), I'm creating my custom modules and DI is working fine for me.

However, I notice that there is a Logger property in the NinjectHttpApplication class, so I'm trying to use this in Application_Error whenever an exception is not caught.

I think I'm creating the nlog module correctly for Ninject, but my logger is always null. Here's my CreateKernel:

protected override Ninject.Core.IKernel CreateKernel()
{
    IKernel kernel = new StandardKernel(new NLogModule(), new NinjectRepositoryModule());
    return kernel;
}

But in the following method, Logger is always null.

protected void Application_Error(object sender, EventArgs e) 
{
    Exception lastException = Server.GetLastError().GetBaseException();
    Logger.Error(lastException, "An exception was caught in Global.asax");
}

To clarify, Logger is a property on NinjectHttpApplication of type ILogger and has the [Inject] attribute

Any idea how to inject correctly into Logger?

A: 

Are you actually wiring up an ILogger in your NLogModule? If not then Ninject probably won't know what to use when you use the Logger of your implemented NinjectHttpApplication class.

I would check what is in your NLogModule, and I would also suggest putting it in your question. I think it might help us to solve your problem.

Joseph
NLogModule isn't my class, it's one I downloaded together with Ninject and it's of type Ninject.Integration.NLog.Infrastructure.NLogModuleWhen I disassemble it with Reflector, it looks like it's doing the business using LogManager.GetLogger
Ciaran
@Ciaran That's interesting. I ready somewhere that you have to specify which ILogger you want to use since it can be a number of different logs (NLog, Log4net just to name a couple). I'm not sure if there is a default set, but you getting null back seems to indicate that there isn't a default. I would play around with explicitly registering some type of ILogger and see if that helps.
Joseph
In my own module, I tried binding the ILogger using:Bind<ILogger>().To<NLogLogger>().Using<SingletonBehavior>();but still not working. Just creating NLog logger the usual way now - it shouldn't be this difficult!
Ciaran
A: 

Download the latest version from GitHub. The logging was removed. The reason you are not seeing the logger injected is that Ninject isn't creating the HttpApplication class, so it doesn't know to inject it, you have to assign it manually. Ninject can only initialize components activated by the kernel.

Ian Davis