Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is a good analogy to understand IoC and DI?

What is a good analogy to understand IoC and DI?

like image 765
GilliVilla Avatar asked Jul 20 '10 16:07

GilliVilla


People also ask

What exactly is IoC and DI How are they related?

Inversion of Control(IoC) is also known as Dependency injection (DI). The Spring container uses Dependency Injection (DI) to manage the components that build up an application and these objects are called Spring Beans. Spring implements DI by either an XML configuration file or annotations.

Is IoC and dependency injection the same thing?

Dependency Injection is the method of providing the dependencies and Inversion of Control is the end result of Dependency Injection. IoC is a design principle where the control flow of the program is inverted. Dependency Injection is one of the subtypes of the IOC principle.

What is Inversion of Control and how does that relate to dependency injection?

The Inversion of Control is a fundamental principle used by frameworks to invert the responsibilities of flow control in an application, while Dependency Injection is the pattern used to provide dependencies to an application's class.

What is difference between IoC and DI in spring?

IOC is a concept where the flow of application is inverted. The control of the logic which is not part of that entity is taken by someone else. DI provides objects that an object needs. So rather than the dependencies construct themselves they are injected.


2 Answers

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.

like image 88
Justin Niessner Avatar answered Sep 18 '22 15:09

Justin Niessner


Martin Fowler does a great job explaining those patterns.

like image 33
Darin Dimitrov Avatar answered Sep 17 '22 15:09

Darin Dimitrov