Tuesday, May 13, 2008

[Arch] Programmatic Dependency Injection

Depdenency Injection is a very cool approach to structure and decouple your software components Depdenency Injection can be seen as a design pattern. Therefore some different implementations of this pattern exisit. You can also write your own DI implementation, but in many cases software developers use existing frameworks like Spring or HiveMind, doing all the hard work. I've found an interesting article about programming dependency injection with an abstract factory. The popular factory pattern is a very common approach to abstract the complex initialisation of service components. Some ideas of the factory pattern can be found in DI framework. This article illustrates an abstract factory pattern with the two following key differences to the traditional factory:
  • An optional factory interface replaces the abstract factory class
  • Every factory method is responsible for creating an object and injecting its dependencies
Based on a simple example with two components he illustrates the following scenarios:
  • Lazy-instantiation of service components
  • Non-Singleton scope (if always a new instance of a object must be created)
  • Wiring up objects dynamically
  • Creation of local stateful objects with dynamic paramters for singletons
To summarize the article:
  • Using factories, developers have to write more code to get started
  • Factory implementation code changes significantly if code changes between lazy-initialization and eager-initialization or from singletons to non-singletons
  • Abstract Factory design pattern include creating local stateful objects from dynamic parameters, handling checked exceptions thrown during object creation, and wiring up objects dynamically
  • Better performance because it uses straightforward Java code and hardwiring
For those who are not familiar with Dependency Injection, look at this simple introduction article, illustrating Dependency Injection with a real life scenario. In this article, the autor also presents a simple implementation of a DI framework, by loading object implementations from a properties file.

Whether you use a DI framework or you implement your own DI, the DI approach brings a clean structure to your software components/systems and unit testing becomes easier by using mock objects. DI frameworks, such as Spring, provide a wide range of additional features, like AOP, Transacation Management, API templates, and some other stuff, which can be also used.

1 comment:

Anonymous said...

Great work. Thanks for the links. DI is an interesting topic!