Thursday, September 07, 2006

The Dependency Injection Pattern: an alternative to Factories and Service Locators

On my vacation I listened to about 30 pod-casts. Although most of what I heard was not new, it still was a good refresher and exciting to listen to. It also inspired me to order a few books and make me think more about what I am doing as software engineer.

One pattern that was new to me is Dependency Injection. It was mentioned in software engineering radio Episode 2 on Dependencies. Instead of using a Factory or a Service Locator (like OSGi), make your class have some members referring to the interfaces it uses. The Dependency Injector then uses either the constructor or some set methods to provide your class with the implementations of the classes your object needs. Read the One minute description and the Two Minute Tutorial of PicoContainer (a nice little Dependency Injection Framework) to see what I mean.

Martin Fowler wrote a long article about Inversion of Control Containers and the Dependency Injection pattern.

I was always wondering why using interfaces when you have only one implementation of the interface anyway. So, why bother? With Dependency Injection you can test your object easyly using Mock Objects. Jeremy Weiskotten wrote an Dr.Dobb's Article on why Dependency Injection is very helpful to create testable and decoupled objects.

Dependency Injection makes it very clear which interfaces your objects depend on. This makes refactoring, testing and understanding code easier. Factories and Service Locators often provide more products than needed by a single class and therefore you cannot really tell what the class depends on.

I'll play with Dependency Injection :-)


  1. If you're excited about dependency injection and want to see the number one showcase for it, try the spring framework

    This is incredible stuff ;-)

  2. Well, what about the Eclipse plugin architecture ? Doesn't that gives RCP applications a bit of DI ?

    I can't find good info about that...