0
0
NestJSframework~30 mins

Provider scope (default, request, transient) in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Provider Scope in NestJS
📖 Scenario: You are building a simple NestJS service that demonstrates how different provider scopes work. This will help you understand how NestJS manages instances of services in different scopes.
🎯 Goal: Create three services with different provider scopes: default (singleton), request-scoped, and transient. Then, inject them into a controller to observe their behavior.
📋 What You'll Learn
Create a service called DefaultService with default scope
Create a service called RequestService with request scope
Create a service called TransientService with transient scope
Inject all three services into a controller called AppController
Add a method in AppController called getScopes() that returns the instance IDs of each service
💡 Why This Matters
🌍 Real World
Understanding provider scopes is essential for building scalable and efficient NestJS applications, especially when managing state or resources per request or per injection.
💼 Career
Many backend developer roles using NestJS require knowledge of provider scopes to optimize performance and resource management in server-side applications.
Progress0 / 4 steps
1
Create DefaultService with default scope
Create a service class called DefaultService with a property id set to a random number using Math.random(). Use the default provider scope (no special decorator needed).
NestJS
Need a hint?

Use @Injectable() without any scope option to create a default singleton service.

2
Create RequestService with request scope
Create a service class called RequestService with a property id set to Math.random(). Use @Injectable({ scope: Scope.REQUEST }) to make it request-scoped. Import Scope from @nestjs/common.
NestJS
Need a hint?

Use @Injectable({ scope: Scope.REQUEST }) to create a request-scoped service.

3
Create TransientService with transient scope
Create a service class called TransientService with a property id set to Math.random(). Use @Injectable({ scope: Scope.TRANSIENT }) to make it transient-scoped. Import Scope from @nestjs/common if not already imported.
NestJS
Need a hint?

Use @Injectable({ scope: Scope.TRANSIENT }) to create a transient-scoped service.

4
Inject services into AppController and add getScopes() method
Create a controller class called AppController. Inject DefaultService, RequestService, and TransientService via the constructor. Add a method called getScopes() that returns an object with keys defaultId, requestId, and transientId holding the id values from each service instance.
NestJS
Need a hint?

Inject the services in the constructor and return their id properties in getScopes().