What is a good analogy to understand IoC and DI?
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.
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.
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.
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.
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.
Martin Fowler does a great job explaining those patterns.
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