What is Dependency Injection?
Wikipedia Definition: Dependency injection is a technique whereby one object (or static method) supplies the dependencies of another object. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client's state. Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern. Now let’s decode this definition with help of real world example:
Let’s say we have a ‘Room’ class which contains various objects such as TV – LG brand, AC- Voltas etc. Here the ‘Room’ class is responsible for creating all the dependency objects. Now, what if we decide to change TV brand from LG to Samsung in future? If we do not use DI then we need to recreate the Room class with object having a new Samsung dependency. But by using dependency injection (DI), we can change the TV brand on the fly because dependencies can be injected at runtime.
DI concept behaves as an intermediary in our code who does all the work of creating the preferred objects and providing it to the class. It makes our class independent from creating the objects.
To get more insight into it, follow our Video tutorial 0008-2- What is Dependency Injection?
Comments