Skip to content

Commit bdda249

Browse files
Merge pull request #2220 from Papooch/docs/clarify-scope-hierarchy
docs(provider-scopes): clarify transient scope hierarchy
2 parents 434ce48 + a0ef420 commit bdda249

File tree

1 file changed

+5
-3
lines changed

1 file changed

+5
-3
lines changed

content/fundamentals/provider-scopes.md

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,10 @@ Similarly, for [custom providers](/fundamentals/custom-providers), set the `scop
4848

4949
> info **Hint** Import the `Scope` enum from `@nestjs/common`
5050
51-
> warning **Notice** Gateways should not use request-scoped providers because they must act as singletons. Each gateway encapsulates a real socket and cannot be instantiated multiple times.
52-
5351
Singleton scope is used by default, and need not be declared. If you do want to declare a provider as singleton scoped, use the `Scope.DEFAULT` value for the `scope` property.
5452

53+
> warning **Notice** Websocket Gateways should not use request-scoped providers because they must act as singletons. Each gateway encapsulates a real socket and cannot be instantiated multiple times. The limitation also applies to some other providers, like [_Passport strategies_](../security/authentication#request-scoped-strategies) or _Cron controllers_.
54+
5555
#### Controller scope
5656

5757
Controllers can also have scope, which applies to all request method handlers declared in that controller. Like provider scope, the scope of a controller declares its lifetime. For a request-scoped controller, a new instance is created for each inbound request, and garbage-collected when the request has completed processing.
@@ -68,10 +68,12 @@ export class CatsController {}
6868

6969
#### Scope hierarchy
7070

71-
Scope bubbles up the injection chain. A controller that depends on a request-scoped provider will, itself, be request-scoped.
71+
The `REQUEST` scope bubbles up the injection chain. A controller that depends on a request-scoped provider will, itself, be request-scoped.
7272

7373
Imagine the following dependency graph: `CatsController <- CatsService <- CatsRepository`. If `CatsService` is request-scoped (and the others are default singletons), the `CatsController` will become request-scoped as it is dependent on the injected service. The `CatsRepository`, which is not dependent, would remain singleton-scoped.
7474

75+
Transient-scoped dependencies don't follow that pattern. If a singleton-scoped `DogsService` injects a transient `LoggerService` provider, it will receive a fresh instance of it. However, `DogsService` will stay singleton-scoped, so injecting it anywhere would _not_ resolve to a new instance of `DogsService`. In case it's desired behavior, `DogsService` must be explicitly marked as `TRANSIENT` as well.
76+
7577
<app-banner-courses></app-banner-courses>
7678

7779
#### Request provider

0 commit comments

Comments
 (0)