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.
Constructor injection in 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.
UsersService into the class so you can use it inside.constructor(private readonly usersService: UsersService) {}constructor(private readonly logger: LoggerService, private readonly config: ConfigService) {}@Inject() to inject a custom provider by its token.constructor(@Inject('CUSTOM_SERVICE') private readonly customService: CustomService) {}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.
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(); } }
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.
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().