0
0
NestJSframework~5 mins

Constructor injection in NestJS

Choose your learning style9 modes available
Introduction

Constructor injection helps you give a class the things it needs to work by passing them in when you create it. This makes your code cleaner and easier to manage.

When you want to give a service or controller access to other services it depends on.
When you want to keep your code organized and easy to test.
When you want NestJS to automatically create and provide the needed parts for your class.
When you want to avoid manually creating instances inside your classes.
When you want to clearly show what a class needs to work.
Syntax
NestJS
constructor(private readonly serviceName: ServiceType) {}

The constructor is a special method that runs when the class is created.

Using private readonly automatically creates and stores the service as a class property.

Examples
This injects the UsersService into the class so you can use it inside.
NestJS
constructor(private readonly usersService: UsersService) {}
You can inject multiple services by adding them as parameters.
NestJS
constructor(private readonly logger: LoggerService, private readonly config: ConfigService) {}
You can use @Inject() to inject a custom provider by its token.
NestJS
constructor(@Inject('CUSTOM_SERVICE') private readonly customService: CustomService) {}
Sample Program

This example shows a HelloService that returns a greeting. The HelloController uses constructor injection to get the service and call its method when handling a GET request.

NestJS
import { Injectable } from '@nestjs/common';

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

import { Controller, Get } from '@nestjs/common';
import { HelloService } from './hello.service';

@Controller()
export class HelloController {
  constructor(private readonly helloService: HelloService) {}

  @Get()
  getHello(): string {
    return this.helloService.getHello();
  }
}
OutputSuccess
Important Notes

Always mark injected services with private readonly to keep them safe inside the class.

Constructor injection works only if the class is decorated with @Injectable() or a similar decorator.

Use constructor injection to make your classes easier to test by replacing dependencies with mocks.

Summary

Constructor injection passes needed services into a class when it is created.

This keeps code clean, organized, and easy to test.

In NestJS, use constructor(private readonly service: ServiceType) inside classes decorated with @Injectable() or @Controller().