13

Possible Duplicate:
Difference between Dependency Injection (DI) & Inversion of Control (IOC)

I'm new to Inversion of Control, Dependency Injection and everything related to these stuff, so excuse me if I'm not specific in my question: Is there any magical piece of code, a good explanation or a link, so I can finally distinguish the concepts?

I really think that using Dependency Injection already means using Inversion of Control, but is there any way of using Inversion of Control without using Dependency Injection?

I've already read Martin Fowler's articles but I still find the concepts very confusing.

2 Answers2

10

Dependency Injection is one way that Inversion of Control is often implemented, but there are others. From the Wikipedia Inversion of control article:

Implementation techniques are influenced by the computer language used.

In Java there are six basic techniques to implement Inversion of Control. These are:

  1. using a factory pattern
  2. using a service locator pattern
  3. using a constructor injection
  4. using a setter injection
  5. using an interface injection
  6. using a contextualized lookup

Constructor, setter, and interface injection are all aspects of Dependency injection.

7

Inversion of Control is a general concept where normal control flow is “inverted” in some way.

By “normal” flow, I mean a traditional batch application flow: the code runs from beginning to end, creating resources, requesting data and providing output. Control flow is dictated by the application itself, calling into libraries and system facilities as necessary. Any inversion of this — where libraries rather than the application (using these terms somewhat loosely) drive control flow — is in some sense inversion of control.

One of the most common examples of IoC is an event loop. In an event loop, the GUI toolkit (or the operating system) is in control, calling back into your application to handle events and process input. The normal flow — requesting input & processing it — is inverted so that the input processor drives the application, rather than the other way around.

Dependency injection is a specific use of Inversion of Control, where control inversion is applied to the selection and allocation of dependencies. Rather than having a component instantiate the subcomponents it requires, the creating code (either application code, manually, or the DI container) instantiates the required subcomponents and injects them into the component.