Monday, March 30, 2009


One important aspect of using a container is that you know multiple layers of the application will be getting information from the container. For this reason, it makes sense to inject the container so that some "higher" level can configure it and pass it around.

For this reason, my business objects take it in the constructor, like this:

public class MyClass : IClass
   public MyClass(IUnity container) 

So how does the container get there? Of course, something has to instantiate and configure it. In a test class, how about the "setup" section? In a web application, what about Global?

At any rate, there is no need to explicitly inject it to the subsequent layers. Configure it, register it, and forget about it.

IUnityContainer container = new UnityContainer();
container.RegisterType<IClass, MyClass>(); 

Unity understands that MyClass needs an IUnityContainer because of the signature of the constructor. By registering the instance of the container itself, when I ask for an IClass, it will reference MyClass and then pass container to satisfy IUnityContainer.

Jeremy Likness