I’m using Unity, and I register a logger like this:
public class MvcApplication : System.Web.HttpApplication
{
private ILogger _logger;
protected void Application_Start()
{
...
var container = new UnityContainer();
container.RegisterType<ILogger, NLogLogger>();
container.RegisterControllers();
DependencyResolver.SetResolver(new UnityDependencyResolver(container));
_logger = container.Resolve<ILogger>();
_logger.Info("Application started");
}
That seems to work fine – the message is logged.
Later in the global.asax.cs I have this:
protected void Application_End()
{
_logger.Info("App is shutting down");
}
protected void Application_Error()
{
Exception lastException = Server.GetLastError();
_logger.Fatal(lastException);
}
However, this throws an exception – _logger is null. I suspect I’m doing something wrong with Unity – so what’s the correct way to use a logger inside global.asax?
You will actually want to re-resolve it from the DependencyResolver in each method where you use it. If you use an Application scoped
LifetimeManagerthen you shouldn’t be incurring any significant performance hit from the constructor. If you are not using an application scopedLiftimeManagerthen at least you won’t be hit with aNullReferenceException!