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.