Performance: Dependency injection basics
Dependency injection affects application startup time and runtime memory usage by managing how services and components are created and shared.
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { getUser() { return { id: 1, name: 'Alice' }; } } import { Controller, Get } from '@nestjs/common'; @Controller('users') export class UserController { constructor(private readonly userService: UserService) {} @Get() getUser() { return this.userService.getUser(); } }
import { Injectable } from '@nestjs/common'; @Injectable() export class UserService { getUser() { return { id: 1, name: 'Alice' }; } } // In a controller or another service const userService = new UserService(); userService.getUser();
| Pattern | Instance Creation | Memory Usage | Startup Time | Verdict |
|---|---|---|---|---|
| Manual service instantiation | Multiple instances per use | High due to duplicates | Slower due to unmanaged creation | [X] Bad |
| NestJS dependency injection | Single shared instance | Lower due to reuse | Faster with centralized control | [OK] Good |
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();
}
}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();
}
}LoggerService and ConfigService, into a controller. Which is the correct way to do this in NestJS?Pass the test and this pattern moves unknown