How does NestJS dependency injection scoping work?
Answer
NestJS providers have three injection scopes: DEFAULT (Singleton): one instance is created for the entire application lifecycle — the default and most performant. REQUEST: a new instance is created for every incoming request. Useful when a provider needs per-request state (e.g., request-scoped user context). Setting a provider as REQUEST-scoped makes all providers that inject it also REQUEST-scoped (scope bubbles up). TRANSIENT: a new instance is created for every injection — each consumer gets its own instance. Declare scope: @Injectable({ scope: Scope.REQUEST }). Use singleton scope by default. Request scope has performance implications due to instance creation overhead for each request and the dependency chain affecting.
Previous
How do you create a custom decorator in NestJS?
Next
What are NestJS microservices and what transports are supported?
More NestJS Questions
View all →- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?
- Intermediate How do you implement caching in NestJS?