I believe that many people are perplexed by the distinction between dependency injection and a dependency injection framework (or a container as it is often called).
The concept of dependency injection is extremely straightforward. Instead of this below
public class A {
private B b;
public A() {
this.b = new B(); // A *depends on* B
}
public void DoSomeStuff() {
// Do something with B here
}
}
public static void Main(string[] args) {
A a = new A();
a.DoSomeStuff();
}
One can use this
public class A {
private B b;
public A(B b) { // A now takes its dependencies as arguments
this.b = b; // look ma, no "new"!
}
public void DoSomeStuff() {
// Do something with B here
}
}
public static void Main(string[] args) {
B b = new B(); // B is constructed here instead
A a = new A(b);
a.DoSomeStuff();
}
That's all there is to it. This provides you with numerous benefits. Two of the most essential are the ability to control functionality from a single location (the Main() function) rather than distributing it throughout your program, and the ability to test each class independently (because you can pass mocks or other faked objects into its function Object() { [native code] } instead of a real value).
The disadvantage is that you now have a single mega-function that knows about all of your program's classes. DI frameworks can assist with this. However, if you're having difficulties grasping why this method is beneficial, I recommend starting with manual dependency injection to gain a better knowledge of what the various frameworks can do for you.