Passing UnityContainer as a dependent

Nov 1, 2012 at 2:19 PM


I guess this is more of a fundamental question for DI...

I'm new to DI / IOC so may have this totally wrong!

In my main class I am loading my unity container from a config file. I then call one or two classes to do most of the work for my app. At the moment I am passing the container down to the class as a dependency injection. The class then uses the container to resolve classes it needs. I keep reading that I should really pass the true dependencies and not the container.

Is there a right and wrong way for doing this?



Nov 1, 2012 at 2:32 PM

You are abusing Unity as a ServiceLocator. Don't. That's an anti-pattern.

Have a look at this question on StackOverflow.

Nov 1, 2012 at 2:46 PM

Perfect answer. Thanks weberse.

Nov 8, 2012 at 9:59 AM

Hmm. OK, I have read quite a lot about DI (yet to get the suggested book) and now I have a bit more of an educated question:

Using DI then dependancies can be passed in via a constructor. Using Unity, these dependancies are resolved automatically. So, if my class hierarchy is only say 4 deep, then are we talking about my root class having to take in the ctor (for example) all the dependancies for all the class below it? If so, what happens when I add some more business logic to my root class which increases dependancies and hence means I have to change my ctor params so that the new set of dependancies can also be injected? This is a breaking change.

I think I'm missing something :(

Thanks for your help



Nov 8, 2012 at 3:57 PM

You won't have to add the dependency at the top level (root) object.  You can add the dependency to the appropriate place in the hierarchy and Unity will inject the object (as long as it can be resolved).  So if the root object has a requirement for a new dependency then that would have to be added to the root object's constructor.

However, Unity is responsible for object construction so as long as the container is configured properly (to allow resolving of the dependency) then the code should not need to change since Unity will handle instantiating the object with the appropriate constructor arguments.

If you are very concerned about breaking changes on an interface (public API) then you would have to manage those carefully.  For example if using a service oriented approach, then you would provide an interface to the consumer and (root) object construction would be done by a factory object using Unity (that the consumer does not know anything about).  It's a similar approach with ASP.NET MVC controllers.

If you are creating more of a Framework like ASP.NET MVC and not a typical application then you will probably have other issues to consider as well and you might consider creating facade classes to allow easy use of the framework without exposing internal details.  This is a good post:

Randy Levy
Enterprise Library support engineer