Implicit request-scope propagation into default-scoped NestJS controllers
0 reputation · 27 Feb 2021, 20:53 UTC
0 reputation · 27 Feb 2021, 20:53 UTC
NestJS's dependency injection system propagates request scope through constructor injection chains, but the extent to which this propagation respects module boundaries remains ambiguous. When a default-scoped controller or provider injects a @Injectable({ scope: Scope.REQUEST }) service, the injected instance appears to adopt request scope even without an explicit annotation on the consuming class. This behavior suggests the DI container's resolution graph at bootstrap may override module-level scope declarations, potentially affecting unrelated consumers in importing modules.
The practical consequence is that a controller designed as a singleton can silently become request-scoped, triggering per-request instantiation of its entire dependency chain and increasing garbage collection pressure under high request throughput. Key uncertainty involves whether scope bubbling is confined to the direct injector-injectee relationship or extends transitively through module export graphs, and how this interacts with microservice or GraphQL execution contexts where request lifecycles differ from standard HTTP.
Does the implicit scope inheritance apply transitively across module export boundaries without explicit @Scope() annotations on consuming classes? Which conditions cause a default-scoped controller to be recreated per-request when a single request-scoped provider is introduced into its dependency tree? When does scope bubbling cross module boundaries, and are there strategies to confine request scope to intended handler boundaries without restructuring the entire dependency graph?
A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.