Dependency Injection in NestJS
Last Updated :
19 Jul, 2024
Dependency Injection (DI) is a fundamental concept in modern software development, enabling developers to create modular, maintainable, and testable code. NestJS, a progressive Node.js framework, uses DI to manage the dependencies of various components in an application. In this article, we'll explore how dependency injection works in NestJS.
What is Dependency Injection?
Dependency Injection is a design pattern that allows an object to receive other objects it depends on, rather than creating them internally. This promotes loose coupling, making code more modular and easier to manage.
How Dependency Injection Works in NestJS
Dependency Injection (DI) in NestJS operates through its Inversion of Control (IoC) container, which automatically manages the representation and injection of dependencies. When a class is marked with the @Injectable() decorator, it becomes a provider that can be injected into other classes. These dependencies are specified in the constructor of a class, and the IoC container resolves them at runtime. This allows for clear and maintainable code, as dependencies are not created manually but injected as needed.
Key Concepts in NestJS DI
- Providers: Classes that can be injected as dependencies. They are usually services or repositories.
- Controllers: Handle incoming requests and return responses.
- Modules: Group related providers and controllers together.
Steps to Implement Dependency Injection
Step 1: Setting Up a NestJS Project
First, create a new NestJS project using the Nest CLI.
npm i -g @nestjs/cli
nest new nest-gfg
cd nest-gfg
Step 2: Creating a Service
Create a service that will be injected into a controller. Services are the most common types of providers.
nest generate service hello
Step 3: Creating a Controller
Create a controller that will use the HelloService.
nest generate controller hello
Folder Structure
Folder StructureDependencies
"dependencies": {
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/mongoose": "^10.0.10",
"@nestjs/platform-express": "^10.0.0",
"dotenv": "^16.4.5",
"mongoose": "^8.5.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1"
}
Example: Implementing basic Dependency Injection
JavaScript
//hello.controller.ts
import { Controller, Get } from '@nestjs/common';
import { HelloService } from './hello.service';
@Controller('hello')
export class HelloController {
constructor(private readonly helloService: HelloService) { }
@Get()
getHello(): string {
return this.helloService.getHello();
}
}
JavaScript
//hello.service.ts
import { Injectable } from '@nestjs/common';
@Injectable()
export class HelloService {
getHello(): string {
return 'Hello, World!';
}
}
JavaScript
//app.module.ts
import { Module } from '@nestjs/common';
import { HelloService } from './hello/hello.service';
import { HelloController } from './hello/hello.controller';
@Module({
imports: [],
controllers: [HelloController],
providers: [HelloService],
})
export class AppModule { }
Run the application using the following command:
npm run serve
Output
Dependency Injection in NestJS
Similar Reads
Angular Dependency Injection
Angular is an open-source framework for building web modern web applications. One of the key principles of Angular is dependency injection. Dependency Injection is one of the widely used techniques in application programming. It is included in almost every framework. In this article, we will learn a
4 min read
What is Global Installation of Dependencies in NodeJS?
Dependencies are packages or libraries that your project requires to function correctly. In NodeJS, dependencies are typically installed using npm (Node Package Manager). These dependencies can either be installed locally (specific to your project) or globally (available system-wide across all proje
4 min read
Installing Dev Dependencies with NPM
When we are building the NodeJS application at that time, we need some of the tools that are not required for production. Such tools are known as the Dev Dependencies. It keeps the production environment free from unnecessary tools, due to which the development becomes smoother and more efficient. W
3 min read
Error Handling In NestJS
NestJS is a progressive, Node.js framework for building efficient and scalable server-side applications. One of the key advantages of NestJS is its powerful dependency injection system and modular structure, which makes building enterprise-level applications more manageable. In this article, we will
5 min read
How to update dependency in package.json file ?
In this article, we will discuss how to update the dependencies of a project with npm. You must have heard about npm which is called a node package manager. So, we can run this command to install an npm package. npm install Note: The --save flag is no longer needed after the Node 5.0.0 version. The
3 min read
How local installation of a dependency done ?
The local installation of dependencies in Node.js is done by putting the local dependencies in a single place and running some simple commands from the terminal to install dependencies. A local dependency can't be accessed outside of the directory. All the local dependencies of a project are usually
2 min read
How to override nested NPM dependency versions?
In projects the packages download and used using npm are called dependency and each dependencies can have their own nested dependencies that also gets downloaded. These nested dependency creates conflicts due to the presence of multiple version of the same dependency. This will lead to issues like c
5 min read
How to use NPM Trends to Pick a Javascript Dependency?
Choosing the right JavaScript dependency for your project can be daunting, given the vast number of available packages. npm trends is a valuable tool that helps developers compare the popularity and usage of npm packages over time. By analyzing download statistics, developers can make more informed
3 min read
What are the different types of dependencies in Node.js ?
NPM (Node Package Manager) is a package manager for the Node JavaScript platform. It consists of an npm registry that enables Open-Source developers to publish and share their code. You might need to install a few packages to streamline your project. Packages contain code written by other developers
4 min read
How to Upgrade NPM Dependencies?
Upgrading NPM dependencies is important to ensure your NodeJS project is updated with the latest features, bug fixes, and security patches This process guarantees compatibility with modern JavaScript environments and increases performance and stability for your projects. NPM (Node Package Manager) i
3 min read