DEV Community

Cover image for What is Dependency Injection + NestJs
Alireza Mohsini
Alireza Mohsini

Posted on

What is Dependency Injection + NestJs

Dependency Injection

Dependency injection is a design pattern used in software engineering that involves injecting dependencies, or external objects, into a class or method instead of having the class or method create or find the objects itself.

With dependency injection, the dependencies are provided to the class or method from outside, typically through constructor injection or setter injection. This makes the code more modular and easier to test, as the dependencies can be easily replaced with mock objects or stubs during testing.

Let's say you have a UserService class that needs to interact with a UserRepository to fetch user data. In traditional software development, you might create an instance of the UserRepository class inside the UserService class. However, with dependency injection, you can inject the UserRepository instance into the UserService class instead.

Here's an example of how to do this in NestJS:

import { Injectable } from '@nestjs/common';
import { UserRepository } from './user.repository';

@Injectable()
export class UserService {
  constructor(private readonly userRepository: UserRepository) {}

  async getUserById(id: string): Promise<User> {
    return this.userRepository.findById(id);
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the UserService class has a constructor that takes an instance of the UserRepository class as a parameter. The @Injectable() decorator tells NestJS that this class is injectable and should be managed by the dependency injection system.

Now, when you want to use the UserService class in another class or module, you can simply import it and let NestJS handle the injection of the UserRepository instance:

import { Module } from '@nestjs/common';
import { UserController } from './user.controller';
import { UserService } from './user.service';
import { UserRepository } from './user.repository';

@Module({
  controllers: [UserController],
  providers: [UserService, UserRepository],
})
export class UserModule {}
Enter fullscreen mode Exit fullscreen mode

In this example, the UserModule imports the UserController, UserService, and UserRepository classes and adds them to the module's providers array. This tells NestJS to create instances of these classes and manage their dependencies using the dependency injection system.

Now, when you call the getUserById method on an instance of UserService, NestJS will automatically inject an instance of UserRepository into the constructor and use that instance to fetch user data. This makes the code more modular and easier to test, as you can easily replace the UserRepository instance with a mock object or stub during testing.

Top comments (0)