node js dependency injection

Node.js Dependency Injection

Dependency injection is a design pattern that allows you to remove hard-coded dependencies and make your code more modular and testable. In Node.js, you can implement dependency injection in several ways.

Constructor Injection

Constructor injection is a way to inject dependencies by passing them as arguments to the constructor of a class or function. Here's an example:


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

  async getUser(id) {
    return this.userRepository.findById(id);
  }
}

// Usage
const userRepository = new UserRepository();
const userService = new UserService(userRepository);
const user = await userService.getUser(123);
  

Setter Injection

Setter injection is a way to inject dependencies by setting them as properties of a class or function after it's been created. Here's an example:


class UserService {
  setUserRepository(userRepository) {
    this.userRepository = userRepository;
  }

  async getUser(id) {
    return this.userRepository.findById(id);
  }
}

// Usage
const userRepository = new UserRepository();
const userService = new UserService();
userService.setUserRepository(userRepository);
const user = await userService.getUser(123);
  

Dependency Injection Containers

A dependency injection container is a way to manage and resolve dependencies automatically. You register your dependencies with the container, and the container takes care of creating an instance of each dependency and injecting it into your classes or functions. Here's an example using the popular library Awilix:


const { createContainer, asClass, asValue } = require('awilix');

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

  async getUser(id) {
    return this.userRepository.findById(id);
  }
}

const container = createContainer();
container.register({
  userRepository: asClass(UserRepository),
  userService: asClass(UserService),
});

// Usage
const userService = container.resolve('userService');
const user = await userService.getUser(123);
  

These are just a few examples of how you can implement dependency injection in Node.js. The key is to decouple your code from its dependencies and make it more modular and testable.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe