Alex Rivera | Logout

Real world solutions using Dependency Injection

Asked 2010-01-21T06:47:26.863
21

I was reading about DI thoroughly, and it seems interesting. So far, I'm totally living without it.

All the examples i saw are related to JNDI and how DI helps you being more flexible.

What is real life applications/problems that you solved with DI that will be hard to solve in other ways?

UPDATE
All the answers till now are educating, but to rephrase the question, I'm looking for examples in your programming life, that made you say "this problem will be best solved with a DI framework".

Edit
Report

2 Answers

3

DI allows you to create applications that can be configured and reconfigured without touching the codebase itself. Not just urls or settings though; generic objects can be written in code, and then "customized" or configured via XML files to achieve the specific result desired for the given case.

For example, I can create a RegexDetective class where the actual regex it looks for is provided in a setter, and then in my Spring DI XML file, define one actual regex expression for RegexDetective.setRegex() for a deployment of SleuthApp going to London. Then a few days later I can go back and update the regex in the XML file for another deployment of SleuthApp shipping out to Siberia.

DI also allows one to define specific implementations of interfaces in a similar fashion, outside of the codebase in XML, to modify behavior of an application without actually touching the code, such as setting the AngryDetective or ArcticDetective implementation of the Detective interface, in the DI XML file.

answered 2010-01-21T07:06:23.027
1

I've used Spring's IoC (DI) container for the last three web apps I've developed. I don't think its suited to one particular type of problem, rather it's a different way of solving a problem. It's as you've said, a more flexible approach to large systems. My personal favourite features of DI are that you can prepare better unit tests because your classes are highly decoupled. Also important for me is code reuse. Since I use the container in many apps, I can use the same components and know that their dependencies will be fed in externally.

answered 2010-01-21T06:52:45.603

Your Answer