This was originally answer I posted to a question on stackoverflow here. Since its popularity I posted it as an article here.
Now both have nothing to do with each other. I really had trouble understanding both so here I go trying to explain.
Dependency Injection: is an implementation (lets call it) of Inversion of Control. You don't confuse the two. You are taking the control of creating an object out of your code. Dependencies, like say a
IRepository would not be created by your classes/code but instead injected by someone else, a dependency injection framework.
Lets say you have:
Now you have an actual implementation:
Now all over the place, you'll have:
Why? Ask yourself why you made an interface in the first place? So you can cope with change. Well now, when you need to change your repository to something else. You have to replace all the lines that have
A simple method is user a factory method which is another form of IOC.
And use it like this:
Now when you have to change your repository you have to change only your factory. Dependency injection takes this to the next level by doing all the work. You don't need to change the code at all (or maybe a few declarations).
A Mocking Framework : Boy this was like rocket science to me. But Steven Sandersons book had a brilliant simple explanation.
We keep going on with the
Now you have to test some complicated UI/Authentication whatever that depends on
Now in your test, when you make
IUserRepository an instance of
MyUserRepo. If something goes wrong you don't know what went wrong! Was it your user control or your database connection?
You want make the test more deterministic as someone said.
So you make a fake user repository.
So now, when you pass this fake repo. If you're test fails you KNOW it was something else, not the data base.
My example was simple, but if its a large number of Interfaces. You'll need to write a lot of fake code, its a lot of code bloat!
So you can use a mocking framework to write less code here.
Moq uses a fluent interface and is quite nice. Using Moq would look like this:
Creating fake objects becomes a lot easier =)
Now I hope your seeing how you can use both to your advantage. You can create your fake objects with a mocking framework, then use dependency injection to hook up the right objects at the right time.
For my smaller Silverlight applications I use MEF (Inbuilt in .Net4) for Dependency Injection. And then I have little
#Ifdef on the declarations for which classes to
Export (or expose) Based on a
#define symbol. So I just change one
#define and I can switch my app to using fake classes here and there.
Really Hope that was helpful.