import { Injectable } from '@nestjs/common'; @Injectable() export class MyService { id = Math.random(); } // This service is injected into two different controllers or providers.
In NestJS, providers with default scope are singletons. This means only one instance is created and shared across the whole app.
import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.REQUEST }) export class RequestService { id = Math.random(); } // This service is injected into controllers handling HTTP requests.
Request-scoped providers create a new instance for each incoming HTTP request, ensuring isolated state per request.
import { Injectable, Scope } from '@nestjs/common'; @Injectable({ scope: Scope.TRANSIENT }) export class TransientService { id = Math.random(); } // Injected multiple times in the same request or component.
Transient providers create a new instance every time they are injected, even within the same request or component.
import { Injectable, Scope } from '@nestjs/common'; @Injectable() export class DefaultService { id = Math.random(); } @Injectable({ scope: Scope.REQUEST }) export class RequestService { id = Math.random(); } @Injectable({ scope: Scope.TRANSIENT }) export class TransientService { id = Math.random(); } // Assume these are injected twice in the same request and their ids logged.
Default scope creates one instance shared everywhere, so ids are same. Request scope creates one instance per request, so ids same within request. Transient creates new instance every injection, so ids differ.
Transient scope creates a new instance every injection, causing the constructor to run most frequently.
