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.
Dependency injection basics in 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.
import { Injectable } from '@nestjs/common'; @Injectable() export class LoggerService { log(message: string) { console.log(message); } }
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!'; } }
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.
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();
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.
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.
Practice
Solution
Step 1: Understand dependency injection concept
Dependency injection means NestJS automatically gives the needed services to classes without manual creation.Step 2: Compare options with this concept
Only To automatically provide required services to classes describes automatic service provision, others describe manual or unrelated actions.Final Answer:
To automatically provide required services to classes -> Option AQuick Check:
Dependency injection = automatic service provision [OK]
- Thinking you must create service instances manually
- Confusing dependency injection with code organization only
- Believing dependency injection removes classes
Solution
Step 1: Recall NestJS decorators for DI
Classes that can be injected must be marked with @Injectable() decorator.Step 2: Check each option
@Controller is for controllers, @Module for modules, @Service is not a NestJS decorator.Final Answer:
@Injectable() -> Option CQuick Check:
@Injectable() marks injectable classes [OK]
- Using @Controller or @Module instead of @Injectable
- Assuming @Service is a valid NestJS decorator
- Forgetting to add any decorator
appService.getMessage() is called?import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
getMessage() {
return 'Hello from AppService';
}
}
export class AppController {
constructor(private readonly appService: AppService) {}
showMessage() {
return this.appService.getMessage();
}
}Solution
Step 1: Understand injection in constructor
AppController receives AppService instance via constructor injection because AppService is marked @Injectable.Step 2: Trace method call
showMessage calls appService.getMessage(), which returns 'Hello from AppService'.Final Answer:
'Hello from AppService' -> Option BQuick Check:
Injected service method returns message [OK]
- Assuming injection fails without @Module setup
- Expecting AppController message instead
- Confusing method return values
import { Injectable } from '@nestjs/common';
export class UserService {
getUser() {
return 'User data';
}
}
@Injectable()
export class UserController {
constructor(private readonly userService: UserService) {}
fetchUser() {
return this.userService.getUser();
}
}Solution
Step 1: Check decorators on injectable classes
UserService is injected into UserController but lacks @Injectable(), so NestJS cannot inject it.Step 2: Verify other options
Constructor in controller is valid, fetchUser need not be async, and private readonly is correct for injection.Final Answer:
UserService is missing @Injectable() decorator -> Option AQuick Check:
Injectable classes must have @Injectable() [OK]
- Forgetting @Injectable on services
- Thinking constructor is invalid in controllers
- Assuming async is required for injected methods
LoggerService and ConfigService, into a controller. Which is the correct way to do this in NestJS?Solution
Step 1: Recall how to inject multiple services
In NestJS, multiple services are injected by listing them as constructor parameters with access modifiers like private readonly.Step 2: Evaluate options
Use constructor injection with both services as parameters marked private readonly correctly uses constructor injection. Create instances manually inside the controller constructor manually creates instances, breaking DI. Use @Injectable() on the controller and call services statically misuses @Injectable on controller and static calls. Inject only one service and import the other directly injects only one service, which is incomplete.Final Answer:
Use constructor injection with both services as parameters marked private readonly -> Option DQuick Check:
Multiple services injected via constructor parameters [OK]
- Manually creating service instances inside controllers
- Using static calls instead of injection
- Injecting only one service when multiple are needed
Ready to prove it?
Pass the test and this pattern moves unknown
