Performance: Provider scope (default, request, transient)
This affects server response time and memory usage by controlling how often instances of providers are created during request handling.
import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.REQUEST }) export class UserService { // stateful data per request } // New instance per HTTP request avoids shared state
import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.DEFAULT }) export class UserService { // stateful data stored here } // Used in many requests, but state is kept per instance
| Pattern | Instance Creation Frequency | Memory Usage | Response Time Impact | Verdict |
|---|---|---|---|---|
| Default Scope (Singleton) | Once per app lifecycle | Low | Fast | [OK] Good |
| Request Scope | Once per HTTP request | Medium | Moderate | [!] OK |
| Transient Scope | Every injection | High | Slower if overused | [X] Bad if misused |
@Injectable({ scope: Scope.TRANSIENT })
export class MyService {
id = Math.random();
}
If this service is injected twice in the same controller, what will be true about the id values?id propertyid is set to a random number on instance creation, each injection will have a different id.id value. -> Option DPass the test and this pattern moves unknown