4

I spent lot of time in understanding ioc. I never understand how exactly control is inverted in this pattern. Even I am confused with exact meaning of inversion. In normal english - inversion is some thing like reversing, say reversing a cup.

If I consider dependency injection as Ioc. I would like to know where exactly contol is inverted here. I understand here in DI, dependency is inserted from an external entity with the help of constructor, setter ........

But I never understand where the control is inverted here...

Any help appreciated.

Mrchief
  • 75,126
  • 20
  • 142
  • 189
Brainchild
  • 1,814
  • 5
  • 27
  • 52
  • See this : http://stackoverflow.com/questions/5433211/difference-between-dependency-injection-and-mocking-framework-ninject-vs-rhinom/5433231#5433231 – gideon Jan 15 '12 at 08:34

3 Answers3

5

Old style:

Class car
{
  Engine _engine;
   Public Car()
   {
       _engine = new V6();
   }
}

inverted:

Class car
{
   Engine _engine;
    Public Car(Engine engine)
    {
        _engine = engine;
     }
}

var car = new Car(new V4());

The caller has the control instead of the car class

jgauffin
  • 99,844
  • 45
  • 235
  • 372
2

Dependency injection inverses control.

For example a car class needs a engine class. The engine could be any type of engine.

If you don't use DI, the car class would determine the engine type itself, the car class is in control.

When using DI, the code instantiating a car would determine the type of car (by specifying the engine in constructor for example), the calling code is now in control. Control is inverted from car class to calling code.

Robin van der Knaap
  • 4,060
  • 2
  • 33
  • 48
  • Thanks, Nice explanation. In your last sentence (Inversion is inverted from car class to calling code.) what is the exact meaning of inversion and inverted ? Is it "Control is inverted from car class to calling calling code" ? in that case inverted is some thing like moving ?? i really confused with the word invert ... – Brainchild Jan 15 '12 at 08:40
  • Oops, should be control instead of inversion. – Robin van der Knaap Jan 15 '12 at 08:45
  • The control over what type of engine is used is moved from car to the calling code – Robin van der Knaap Jan 15 '12 at 08:48
0

To expand on robin's answer:

IUserRepository _user  = new UserRepository();
//you're in control of which instance is created.

With dependency injection:

IUserRepository _user;// you will not do anything else. 

Based on a configuration somewhere else, the dependency injection framework you use will take care of creating the right instance for you. This is when control is inversed from your code. You are not directly creating any instance from your code.

Why!? Why would you do this?

One major advantage is testing, when you run tests, you can configure your IUserRepository with a fake one.

gideon
  • 19,329
  • 11
  • 72
  • 113