Friday, June 11, 2010

Implementing your own Dependency Injection, Part 2

In my previous post "Implementing Your own DI", I discussed how to implement a simple dependency injection using Java Annotations and Reflection API. In this post, I will discuss about adding some extra features to the previous implementation.

The new features included are:
  • Constructor level injection.
  • Injecting methods with multi-parameters.
  • Resolve dependencies by specifying an id, if not specified use the member's name (field's name or setter method's name) instead, or by class type.
  • Dependencies can be marked as optional.
  • Adding foreign objects. Objects that are not created by this implementation but are dependencies of classes created and wired by this implementation.

Friday, May 14, 2010

Implementing your own Dependency Injection

Dependency Injection can help in improving the quality of your code. DI helps writing code that is more flexible, reusable, and easier to test. Many open source frameworks are available that provide Dependency Injection such as Spring Framework, Google Guice, PicoContainer, etc. I, personally, use Spring with most of my projects. However, in some situations you may not be able to use or may not prefer using one of these frameworks. For example, if you are writing a library for other developers to use, you would not think of using a DI framework (true in my case, I'm a member of SMSLib project). Using a DI framework in a library is not a good idea, since this widens the library's learning curve. In addition, some users may have their own DI framework that might not be compatible with the DI framework used by the library. Usually, DI frameworks are associated with IoC and are meant to be used by end developers which make use of Ioc and DI to integrate different libraries, in addition to their own code, to provide applications for end users. In these cases, where using a DI framework is not an option, you usually end up implementing your own DI for your code.