Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

design pattern
communitycreator

How to use a dependency injection

Samra Fakhar

What is a dependency?

A class or an object (A) is said to be dependent on another object or class (B) when A uses some functionality of B. Traditionally, A is responsible for creating the dependent object B itself.

class A{
  private B b = new B();
  //The rest
}

This approach leads to highly coupled classes. Now, suppose we want to change the type of dependent object from B to some other class, C. We will have to recreate class A with its new dependency, C.

What is a dependency injection?

In simple terms, dependency injection is supplying the objects with that with an object needs, i.e., dependencies, instead of having the object create it themselves. This approach leads to loosely coupled classes, a desirable behavior.

The dependent class is called the Client class. Dependency is referred to as the Service class.

In dependency injection, dependencies are provided to classes at run time rather than at compile time. A dependency injection is sort of the middleman in our code, as it does all the work of creating the desired dependency object B and providing it to class A.

class A{

  // Constructor Injection
  private B b;

  A(B b) {
      this.b = b;
  }

  //Setter injection
  void setB(B b) {
      this.b = b;
  }
}

Types of dependency injections

Constructor injection: A class constructor supplies the dependencies.

Setter injection: Injector injects the dependency through a setter method exposed by the client.

Interface injection: Injector class injects the dependency object into the dependent class.

Advantages of dependency injection

  1. Enables loose coupling.
  2. Helps in unit testing.
  3. Simplifies extending the application.
  4. Reduces boilerplate code.

RELATED TAGS

design pattern
communitycreator
RELATED COURSES

View all Courses

Keep Exploring