Sobes.tech
Middle

What is Dependency Injection?

sobes.tech AI

Answer from AI

This is a design pattern where component dependencies are not created by the component itself but are provided from outside. This increases flexibility, testability, and maintainability of the code.

There are three main types of dependency injection:

  • Constructor Injection: Dependencies are passed into the object's constructor.
  • Setter Injection: Dependencies are passed through public setter methods.
  • Interface Injection: The object implements an interface that contains a method for injecting the dependency. (Less common in Node.js)

Example of constructor injection:

// Dependency: a service for working with the database
class DatabaseService {
  query(sql) {
    // Implementation of the query
    console.log(`Executing SQL: ${sql}`);
  }
}

// Component using the service
class UserService {
  constructor(dbService) {
    this.dbService = dbService;
  }

  getUserById(userId) {
    this.dbService.query(`SELECT * FROM users WHERE id = ${userId}`);
  }
}

// Creating instances and injecting dependency
const db = new DatabaseService();
const userSvc = new UserService(db);

userSvc.getUserById(123);

Advantages of DI:

  • Testability: Easier to replace real dependencies with mocks or stubs.
  • Flexibility: Components become less coupled to specific implementations of dependencies.
  • Maintainability: Changes in one part of the system have less impact on others.
  • Reusability: Components become more reusable.

In Node.js, frameworks like NestJS (which uses its own IoC container) or libraries like InversifyJS are often used to implement DI.

What is Dependency Injection? — Node.js - sobes.tech