Dependency InjectionSeparating the Container

time to read 2 min | 358 words

In a previous post, I made the statement that I believe that using an IoC container should be transparent to the application code, and that a good IoC can and should be invisible to anything but the Main() method.

I would like to expand a bit on this topic, cover the sample problem that Tobias had brought up:

I never could achieve this and I'm wondering, what you mean by this statement. There a are always a lot of references to the DI/IoC container throughout the application. E.g. each IView that needs to be created to show a WinForm requires to ask the Container to give me the instances:


It might be an IController as well and IView is automatically resolved by the container, but as long as I need to instantiate new objects dynamically, I need to reference the IoC container at serveral places outside Main(). Maybe in very simple cases, the whole object tree required during the lifecycle of the application can be set up in Main().

Tobias has indeed hit the nail on the head, lifecycle issues are the one thing that can cause a lot of issues there. I would preface this by saying that I do not always follow this advice fully, and I have no compunctions about using the IoC as a service locator where appropriate, but I would try to limit it to the infrastructure part of the application only.

In this scenario, what I would generally do is define something like this:

// infrastructure service
public interface IRedirectionService
	IRedirectionOperation To<TController>();

And then use it like this:


It depends on the given scenario, but in this case, I am handing control from one controller to the other, and waiting until the second controller is done doing its job (think about it like modal dialog).

The Redirection Service is responsible for creating the controller / view (or find them if they are already active), and activate them.

IoC & DI are under the cover, but I don't have it in my face, and I have nice API against which I can work.

More posts in "Dependency Injection" series:

  1. (23 Aug 2007) Separating the Container
  2. (21 Aug 2007) Applicability, Benefits and Mocking
  3. (18 Aug 2007) IAmDonQuixote ?
  4. (18 Aug 2007) More than a testing seam