0
0
NestJSframework~5 mins

Dependency injection basics in NestJS

Choose your learning style9 modes available
Introduction

Dependency injection helps you give parts of your app what they need without making them find it themselves. It keeps your code clean and easy to change.

When you want to share a service like a database connection across different parts of your app.
When you want to make your code easier to test by swapping real services with fake ones.
When you want to organize your app so each part only focuses on its job.
When you want to avoid creating objects manually and let NestJS handle it for you.
Syntax
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class MyService {
  getHello(): string {
    return 'Hello!';
  }
}

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

@Controller()
export class MyController {
  constructor(private readonly myService: MyService) {}

  @Get()
  getHello(): string {
    return this.myService.getHello();
  }
}

@Injectable() marks a class as a service that can be injected.

The service is added to the constructor of the class that needs it, and NestJS provides it automatically.

Examples
This is a simple service that logs messages to the console.
NestJS
import { Injectable } from '@nestjs/common';

@Injectable()
export class LoggerService {
  log(message: string) {
    console.log(message);
  }
}
The controller uses the LoggerService injected via the constructor to log a message before returning a response.
NestJS
import { Controller, Get } from '@nestjs/common';
import { LoggerService } from './logger.service';

@Controller('hello')
export class HelloController {
  constructor(private readonly logger: LoggerService) {}

  @Get()
  sayHello(): string {
    this.logger.log('Saying hello');
    return 'Hello World!';
  }
}
Sample Program

This simple NestJS app shows dependency injection by providing GreetingService to AppController. When you visit the root URL, it returns a greeting message from the service.

NestJS
import { Injectable, Controller, Get, Module } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';

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

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

  @Get()
  getGreeting(): string {
    return this.greetingService.getGreeting();
  }
}

@Module({
  controllers: [AppController],
  providers: [GreetingService],
})
class AppModule {}

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  await app.listen(3000);
  console.log('Application is running on http://localhost:3000');
}

bootstrap();
OutputSuccess
Important Notes

Always mark services with @Injectable() so NestJS can inject them.

Use constructor injection to get services where you need them.

Dependency injection helps keep your code easy to test and maintain.

Summary

Dependency injection lets NestJS provide needed services automatically.

Mark services with @Injectable() and inject them via constructors.

This keeps your code clean, testable, and organized.