All quizzesHard
Scopes & Advanced DI — Series 3
Preview — 3 of 10 questions
What should you expect from these hooks?
javascript
@Injectable({ scope: Scope.REQUEST })
export class TenantContext implements OnModuleInit, OnModuleDestroy {
onModuleInit() { /* never runs? */ }
onModuleDestroy() { /* never runs? */ }
}AThey fire once per request, replacing the module-level semantics
BonModuleInit fires per request while onModuleDestroy fires once at shutdown
CThey fire once at bootstrap against a prototype instance
DModule-lifecycle hooks are tied to the module's lifecycle, and a request-scoped provider has no instance at that time — so they are not invoked for it; per-request setup belongs in the constructor or in an explicit initialisation the consumer calls
What is the outcome?
javascript
@Injectable({ scope: Scope.REQUEST })
export class RequestUser { constructor(@Inject(REQUEST) readonly req: Request) {} }
@Injectable() // default scope
export class AuditService { constructor(private readonly user: RequestUser) {} }AStartup fails: a default-scoped provider may not depend on a request-scoped one
BAuditService is promoted to request scope automatically — the declared scope is a floor, not a ceiling, so it is instantiated per request along with everything that depends on it
CAuditService stays a singleton and receives the first request's RequestUser
DAuditService receives a proxy that resolves the current request lazily
What does injecting @Inject('LOGGER') produce?
javascript
@Injectable({ scope: Scope.TRANSIENT })
export class Logger {}
@Module({
providers: [Logger, { provide: 'LOGGER', useExisting: Logger }],
})
export class AppModule {}AThe alias resolves to the target token, so the target's scope governs: 'LOGGER' behaves like Logger and yields a transient instance per consumer, because useExisting is an indirection rather than a second registration
BA default-scoped singleton, since the alias declares no scope of its own
CA resolution error, because a scoped provider cannot be aliased
DA frozen snapshot of the first Logger instance created
Sign up free to play
Answer all 10 questions (7 more), see explanations for every answer, and track your score.