All quizzesHard
Scopes & Advanced DI
Preview — 3 of 10 questions
What happens when a provider is declared with Scope.REQUEST?
javascript
import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core';
import { Request } from 'express';
@Injectable({ scope: Scope.REQUEST })
export class RequestContext {
constructor(@Inject(REQUEST) private readonly req: Request) {}
get userId(): string | undefined { return this.req.user?.id; }
}AOne instance is created at bootstrap and reused forever
BThe provider becomes globally shared across requests
CA new instance is created on every method call
DA new instance is created per incoming request (per DI sub-tree identified by a ContextId), so it can safely hold request-specific state
How does Scope.TRANSIENT differ from REQUEST scope?
javascript
import { Injectable, Scope } from '@nestjs/common';
@Injectable({ scope: Scope.TRANSIENT })
export class ScopedLogger {
private context = '';
setContext(name: string): void { this.context = name; }
}
// Each consumer gets a separate ScopedLogger instance.ATRANSIENT shares one instance per request
BTRANSIENT is the default scope
CTRANSIENT gives each consumer that injects the provider its own dedicated instance, independent of requests
DTRANSIENT instances are never garbage collected
A singleton provider injects a REQUEST-scoped provider. What is the effect?
javascript
@Injectable({ scope: Scope.REQUEST })
export class Tenant {}
@Injectable() // becomes effectively REQUEST-scoped due to bubbling
export class ReportService {
constructor(private readonly tenant: Tenant) {}
}AThe singleton is "promoted" so the dependent chain effectively becomes request-scoped (scope bubbles up)
BNest throws an error — singletons can't inject scoped providers
CThe REQUEST-scoped provider silently becomes a singleton
DNothing changes; both keep their original scope independently
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.