views:

94

answers:

3

What is a good analogy to understand IoC and DI?

+1  A: 

Martin Fowler does a great job explaining those patterns.

Darin Dimitrov
+2  A: 

There are a couple of different analogies that make understanding Inversion of Control easier. We experience this in many different ways in regular life, so we are borrowing the form in code. One analogy is called the "Chain of Command" in the military.

This is probably the clearest parallel to Inversion of Control. The military provides each new recruit with the basic things he needs to operate at his rank, and issues commands that recruit must obey. The same principle applies in code. Each component is given the provisions it needs to operate by the instantiating entity (i.e. Commanding Officer in this analogy). The instantiating entity then acts on that component how it needs to act.

More here:

Does anyone have a good analogy for dependency injection?

Leniel Macaferi
+4  A: 

If you take the classic example of a Car. You could go through the regular car buying process and take the wheels the manufacturer gives you:

public class Fifteens
{
    public void Roll() { Console.WriteLine("Nice smooth family ride..."); }
}

public class Car
{
    Fifteens wheels = new Fifteens();

    public Car() { }

    public void Drive() { wheels.Roll; }
}

Then:

Car myCar = new Car(); 
myCar.Drive() // Uses the stock wheels 

Or you could find a custom Car builder which allows you to specify exactly what kind of wheel you want your Car to use, as long as they conform to the specifications of a wheel:

public interface IWheel
{
    void Roll();
}

public class Twenties : IWheel
{
    public void Roll() { Console.WriteLine("Rough Ridin'...");
}

public class Car
{
    IWheel _wheels;

    public Car(IWheel wheels) { _wheels = wheels; }

    public void Drive() { wheels.Roll(); }
}

Then:

Car myCar = new Car(new Twenties()); 
myCar.Drive(); // Uses the wheels you injected.

But now you can inject whatever kind of wheel you want. Keep in mind that his is just one kind of Dependency Injection (constructor injection) but it serves as one of the easiest examples.

Justin Niessner