Dependency Injection

-> is a software design pattern that implements inversion of control for resolving dependencies.
-> is a style of object configuration in which object’s fields and collaborators are set by an external entity.   In other words objects are configured by an external entity.
-> using DI objects are given their dependencies at run time rather than compile time.
-> It helps us to create loosely coupled classes.
-> When two classes are tightly coupled, they are linked with a binary association. You might have two classes Class1 and Class2 that are joined together as an aggregation.

Three types of DI

Constructor Injection
– The dependencies are provided through a class constructor.

Setter Injection
– The client exposes a setter method that the injector uses to inject the dependency.

Interface Injection
– The dependency provides an injector method that will inject the dependency into any client passed to it. Clients must implement an interface that exposes a setter method that accepts the dependency

Uses of DI

Unit Testing

Validation/Exception Management
-> DI allows us to inject additional code between the dependencies. It is possible to inject exception management logic or validation logic, which means that developer no longer needs to write logic for every class.

Leave a Reply

Your email address will not be published. Required fields are marked *