I am new in Magento 2.

I wanted to know, what is dependency injection in magento 2.

What the concept is about, and how to use it in our framework ?

I have referred this documentation

But still haven't got the concept correctly.


Inside a project, classes interact with each other.
So we can say, a class depends on other classes.
And there are 2 ways the connection can be made.

  1. The class locates its dependencies.
  2. The dependencies are provided to the class.

Magento 1 takes the first approach. Here is a random example. In this example, the category model depends on the url rewrites instance. So it instantiates it.

Magento 2 takes the second approach.

When building a class, all the dependencies are specified in the constructor.
When used, the class is instantiated via a factory method that reads the signature of the class constructor, to check what dependencies are required.

Magento 2 also has a dependency injection container (DIC) which is basically a big array with the classes that get instantiated.
When trying to instantiate a class, it checks if it's dependencies are already present in the DIC.
If they are, they are provided to the constructor, if not, the dependency class is instantiated in the same way as the current class you are trying to instantiate.

This is it in a nutshell. In practice is a bit more complicated because configuration files are involved also (di.xml), some dependencies might be interfaces which cannot be instantiated, but this factory method supplies a class that implements that interface when your class gets instantiated, based on the contents of the same di.xml file.
Also some dependencies are not objects. They can be arrays, string, ... They are supplied to the class via the same di.xml file.

If you want to dig and see how it actually happens, you can start from this class https://github.com/magento/magento2/blob/develop/lib/internal/Magento/Framework/ObjectManager/Factory/Dynamic/Developer.php.
But it's not an easy thing to follow. You need some patience.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.