unitycontainer / aspnet-mvc

ASP.NET MVC 5 Adapter
Apache License 2.0
13 stars 10 forks source link

UnityPerRequestHttpModule is disposing instances with container controlled lifetime #19

Open ArnaudB88 opened 3 years ago

ArnaudB88 commented 3 years ago

Hi, I recently found a bug where my singleton instance (logger) is disposed at the beginning of my MVC web application. On the first 'end request' event of the web application, the logger is disposed. Looking at the call stack, it seems the UnityPerRequestHttpModule.OnEndRequest() disposes all items on the context. The item list contains the container controlled instance of my logger.

Some code: In the container registrations I have: container.RegisterSingleton<Common.Interfaces.ILogger, SerilogLogger>();

I added an 'Application_EndRequest()' method on the global.asax class of my web application, simply showing me all registered items in the HTTPContext. A screenshot proving that the singleton instance is present in that items list (3th item): image

That same list is processed by the UnityPerRequestHttpModule.OnEndRequest(). Only instances with the PerRequestLTM should be disposed I guess.

Important note: this issue only appears when the singleton logger is needed by a PerRequest registered class and first resolved for that class. When the singleton logger is already resolved before needed by a PerRequest registered class, this issue doesn't appear. The items list (screenshot above) is the same, except the logger instance is missing in that list.