Using the Ninject NLogModule Logger in global.asax
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.开发者_Go百科
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?
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.
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.
精彩评论