Register and use the registrar with Unity in global.asax

I use Unity, and I register the registrar as follows:

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"); } 

It seems to be working fine - the message is being logged. Later in global.asax.cs I have the following:

  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 right way to use the logger inside global.asax?

+6
source share
2 answers

You really want to re-enable it from DependencyResolver in every method in which you use it. If you are using an application with a LifetimeManager scope, you should not be exposed to a significant performance hit from the constructor. If you are not using an application with a LiftimeManager , then at least you will not 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); } } 
+3
source

Another way is to make the log static:

 private static ILogger _logger; 

Of course, your log implementation should be thread safe.

0
source

Source: https://habr.com/ru/post/888637/


All Articles