DI – Unity.Mvc3 and Object reference not set to an instance of an object.
This article was originally published for www.prowareness.com and could be located at http://www.prowareness.com/blog/di-unity-mvc3-and-object-reference-not-set-to-an-instance-of-an-object/
When you use Unity.Mvc3 or Unity.Mvc4 for DI, odds are you might not even run in to the below exception/stack trace.
But you’d never know what kind of system you are dealing with. By name, these dlls – Unity.Mvc3, and Unity.Mvc4 – imply that they need to be used with MVC applications; which means, they are many things related to a web page or web request that this dll might possibly expect, for instance, the web context, the authorization context, routing context and so on.
We were dealing with a system where we tried using Unity.Mvc3 for dependency injection, and a very few parts of existing functionalities started failing with the below stack trace.
This exception occurred because we invoke a background worker from the UI (to run a long running Task), and when the background worker finishes, it would call in RenderViewToString, and update the UI. During the second part a System.NullReferenceException was thrown. With the given stack trace it was evident that this was happening due to the Unity.Mvc3 at Unity.Mvc3.UnityDependencyResolver.get_ChildContainer().
Searching internet yielded no results. We went and looked at the Unity.Mvc3 source code at and found that property named ChildContainer was expecting a HttpContext and our BackgroundWorker didn’t have that for obvious reasons. Hence the Object reference not set to an instance of an object.
Credits to Brijesh, where he had it spot on when he saw the word HttpContext. We ended up removing Unity.Mvc3 completely and used the infamous custom dependency resolver implementing the System.Web.Mvc.IDependencyResolver interface.