Register and use a logger with Unity in 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 LifetimeManager
then you shouldn't be incurring any significant performance hit from the constructor. If you are not using an application scoped LiftimeManager
then at least you won't be hit with a NullReferenceException
!
protected void Application_End(){ var logger = DependencyResolver.Current.GetService<ILogger>(); if(logger != null) { logger.Info("App is shutting down"); }}protected void Application_Error(){ Exception lastException = Server.GetLastError(); var logger = DependencyResolver.Current.GetService<ILogger>(); if(logger != null) { logger.Fatal(lastException); }}
Another way is to make the logger static:
private static ILogger _logger;
Your logger implementation has to be thread safe, of course.