Possible Duplicates:
Difference between Dependency Injection (DI) & Inversion of Control (IOC)
Inversion of Control < Dependency Injection
Hey, This is a Scott Hanselman interview question. I always find this question hard to answer. May be parts of this question could be answered on stack but on a whole this is very important.
I would also like to know other forms of IoC apart from DI.
Can someone explain me with some real time examples.
Thanks
Dependency injection is not a form of IoC. Inversion of Control is a pattern that's not related to DI at all, except for the fact that they're usually used together in some sort of framework, which lead people to think they're the same thing when they're not.
Dependency injection just means that you inject a class's dependencies into it, through a constructor or a series of setters, rather than instantiating them in the class. It can be done without an IoC container of any sort, completely manually.
A really simple example of manual DI could be:
import org.apache.http.client.HttpClient;
public class TwitterClient {
private HttpClient httpClient;
public TwitterClient(HttpClient httpClient){
this.httpClient = httpClient;
}
}
Whenever you create a TwitterClient in your code, you would have to also create an HttpClient and pass it in. Since this would be rather tedious, there are frameworks to make it easier, but as I mentioned it's totally possible to do it manually. This article touches on manual DI - http://googletesting.blogspot.com/2009/01/when-to-use-dependency-injection.html, and in fact early versions of some Google produces were built entirely around manual DI.
The benefit here is that you can swap out the implementations, so if you wanted to pass in a stubbed-out client for unit testing purposes it's easy. Otherwise, there would be no real way to unit test a class like that.
IoC means that you've got some sort of framework that's in control of the application's lifecycle. A good example of IoC that doesn't involve DI would be just about any of the Cocoa apple frameworks, that control the lifecycle of a Cocoa app. You implement certain methods that get called at certain points in the lifecycle of the app. That's why it's the "Hollywood principle", you don't call the framework, the framework calls you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With