Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Register and use a logger with Unity in global.asax

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?

like image 454
Matt Frear Avatar asked May 20 '11 11:05

Matt Frear


1 Answers

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);
    }
}
like image 81
Ethan Cabiac Avatar answered Nov 01 '22 22:11

Ethan Cabiac