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 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With