Computers, Programming, Technology, Music, Literature

DI – Unity.Mvc3 and Object reference not set to an instance of an object.

leave a comment »


This article was originally published for and could be located at


When you use Unity.Mvc3 or Unity.Mvc4 for DI, odds are you might not even run in to the below exception/stack trace.

   at Unity.Mvc3.UnityDependencyResolver.get_ChildContainer()
   at Unity.Mvc3.UnityDependencyResolver.GetService(Type serviceType)
   at System.Web.Mvc.BuildManagerViewEngine.DefaultViewPageActivator.Create(ControllerContext controllerContext, Type type)
   at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)


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.


Written by gmaran23

September 27, 2013 at 9:58 am

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: