0
0
NestjsConceptBeginner · 3 min read

What is Dependency Injection in NestJS: Simple Explanation and Example

In NestJS, dependency injection is a design pattern that allows you to provide components or services to other parts of your app automatically. It helps manage how objects get created and connected, making your code easier to organize and test.
⚙️

How It Works

Dependency injection in NestJS works like a helpful assistant who hands you the tools you need exactly when you need them, without you having to find or create them yourself. Instead of creating objects manually inside your classes, NestJS automatically provides the required objects (called dependencies) for you.

Imagine you are baking a cake and need eggs, flour, and sugar. Instead of going to the store yourself, someone brings these ingredients to your kitchen ready to use. This is how dependency injection saves time and keeps your code clean by managing dependencies centrally.

In NestJS, this is done using decorators and a built-in container that keeps track of all the services and components. When a class needs a service, NestJS injects it automatically, so your classes focus only on their main job.

💻

Example

This example shows a simple service being injected into a controller in NestJS. The service provides a greeting message, and the controller uses it without creating the service manually.

typescript
import { Injectable, Controller, Get } from '@nestjs/common';

@Injectable()
export class GreetingService {
  getGreeting(): string {
    return 'Hello from GreetingService!';
  }
}

@Controller()
export class AppController {
  constructor(private readonly greetingService: GreetingService) {}

  @Get()
  getHello(): string {
    return this.greetingService.getGreeting();
  }
}
Output
Hello from GreetingService!
🎯

When to Use

Use dependency injection in NestJS whenever you want to keep your code organized, reusable, and easy to test. It is especially helpful when your app grows and you have many services or components that depend on each other.

For example, use it to inject database services, logging tools, or configuration settings into your controllers or other services. This way, you can swap or mock these dependencies easily without changing the main code.

Key Points

  • Dependency injection automatically provides required services to classes.
  • It improves code organization and testing.
  • NestJS uses decorators like @Injectable() and constructor injection.
  • It helps manage complex dependencies in large applications.

Key Takeaways

Dependency injection in NestJS automatically supplies needed services to classes.
It keeps your code clean, organized, and easier to test.
Use decorators like @Injectable() to mark services for injection.
It is essential for managing dependencies in growing applications.