DEV Community

teaganga
teaganga

Posted on • Edited on

Depedency Injection Principle in JavaScript

Dependency Injection Principle (DI or DIP) is the most important of the SOLID design principles used in software development. It is used in many object oriented languages and we can use it in java JavaScript too, even if Javascript is not a purely object oriented design.

However, Dependency Injection principle is crucial to achieve loose coupling and improve the maintainability, testability, and flexibility of code.

The main intent of the dependency injection patter is rather than a component creating its own dependencies directly, they are provided with dependencies created from the outside, making components more modular and easier to manage, as they don't need to know the intricate details of how their dependencies are created or obtained.

Let's see a few examples where Dependency Injection Pattern is used:

Constructor Injection

The database is injected through the constructor:

class UserService {
  constructor(database) {
    this.database = database;
  }

  getUser(id) {
    return this.database.query(`SELECT * FROM users WHERE id = ${id}`);
  }
}
Enter fullscreen mode Exit fullscreen mode

Method Injection

class UserController {
  getUser(id, userService) {
    return userService.getUser(id);
  }
}

const userService = new UserService();
const userController = new UserController();

const user = userController.getUser(123, userService);

Enter fullscreen mode Exit fullscreen mode

Property Injection

class OrderService {
  // No constructor injection, dependencies assigned directly
  productService;

  constructor() {
    // ...
  }

  setProductService(productService) {
    this.productService = productService;
  }

  // ...
}
Enter fullscreen mode Exit fullscreen mode

Using a Dependency Injection Container

A DI container manages the creation and injection of dependencies, centralizing the configuration and management of dependencies. Libraries like InversifyJS, Awilix, and Angular's built-in DI system provide containers.

const { Container } = require('inversify');

const container = new Container();
container.bind('userService').to(UserService);

const userService = container.get('userService');
Enter fullscreen mode Exit fullscreen mode

You can check more design patterns and design principles posts:

Top comments (0)