The {scope: Scope.REQUEST} option changes the lifetime of the instances of this provider. By default, providers in NestJS are singletons, meaning that NestJS creates one instance of each provider and reuses it across the application.
When you set scope: Scope.REQUEST, it changes this behavior. Instead of creating a single instance of the provider, NestJS creates a new instance for each incoming request and disposes of it when the request is done. This is useful when you need to have request-specific data or behavior in your provider.
Here's a brief explanation of the different scopes:
Scope.DEFAULT: This is the default scope. Providers with this scope act as singletons.
Scope.REQUEST: Providers with this scope are created for each incoming request.
Scope.TRANSIENT: Providers with this scope are created each time they're injected or retrieved from the NestJS dependency injection container.
Remember that using request-scoped providers can have an impact on performance, because a new instance is created for every request. So, use them judiciously.
In this example, RequestScopedService is a service with scope: Scope.REQUEST. It has a requestTime property set to the current timestamp when the service is created. This service can be injected into other components, and a new instance will be created for each incoming request.
Share this post
Understanding Provider Scopes in NestJS
Share this post
The
{scope: Scope.REQUEST}
option changes the lifetime of the instances of this provider. By default, providers in NestJS are singletons, meaning that NestJS creates one instance of each provider and reuses it across the application.When you set
scope: Scope.REQUEST
, it changes this behavior. Instead of creating a single instance of the provider, NestJS creates a new instance for each incoming request and disposes of it when the request is done. This is useful when you need to have request-specific data or behavior in your provider.Here's a brief explanation of the different scopes:
Scope.DEFAULT
: This is the default scope. Providers with this scope act as singletons.Scope.REQUEST
: Providers with this scope are created for each incoming request.Scope.TRANSIENT
: Providers with this scope are created each time they're injected or retrieved from the NestJS dependency injection container.Remember that using request-scoped providers can have an impact on performance, because a new instance is created for every request. So, use them judiciously.
In this example,
RequestScopedService
is a service withscope: Scope.REQUEST
. It has arequestTime
property set to the current timestamp when the service is created. This service can be injected into other components, and a new instance will be created for each incoming request.