Where control is inverted to control inversion

I spent a lot of time understanding ioc. I never understand how exactly control is inverted in this template. Even I am confused with the exact inversion value. In ordinary English, inversion is something like reversing, say, reversing a cup.

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

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

Any help was appreciated.

+4
source share
3 answers

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()); 

Caller has control instead of car class

+5
source

Injection dependency injection control.

For example, a car class requires an engine class. The engine may be any type of engine.

If you do not use DI, the car class will determine the type of engine itself, the car class is under control.

When using DI, the code that creates the car instance will determine the type of car (for example, specifying the engine in the constructor), the calling code is now under control. Control is inverted from the vehicle class to the calling code.

+2
source

To extend the answer to robin:

 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 infrastructure you are using will take care of creating the right instance for you. This is when management accesses from your code. You do not arbitrarily create any instance from your code.

Why!? Why would you do this?

One of the main advantages is testing, when you run tests, you can configure your IUserRepository fake.

0
source

Source: https://habr.com/ru/post/1391077/


All Articles