CodePark/ questions / Providers & dependency injection
START PRACTICINGPRACTICE
Backend question · NestJS › Providers & dependency injection

CatsController (default scope) injects CatsService (default scope), which injects TenantContext declared with scope: Scope.REQUEST. What scope do the controller and service effectively have?

Both CatsService and CatsController become request-scoped

Both CatsService and CatsController become request-scoped. Request scope bubbles up the injection chain. Anything that depends on a request-scoped provider, directly or indirectly, must also be created per request.

"Both stay singletons; only
TenantContext is recreated per request" is wrong, because a singleton can't hold a per-request object. "Nest throws at startup because a singleton cannot depend on a request-scoped provider" is also wrong. Nest does not throw. It quietly promotes the whole chain. This is why one request-scoped provider deep in the graph can hurt performance.