Dependency injection and scopes
Framework lane: NestJS 11.x candidate, TypeScript legacy decorators and emitDecoratorMetadata, compatible reflect-metadata and RxJS. Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages. A decorator such as @Controller attaches framework metadata; a TypeScript annotation describes a compile-time contract. The full TypeScript chapter follows this introduction. Use a reviewed Nest TypeScript project, not node directly on the .ts file.
Framework example — staged
import { Inject, Injectable, Module } from '@nestjs/common';export const STOCK = Symbol('STOCK');interface Stock { count(): number; }@Injectable()export class InventoryService { constructor(@Inject(STOCK) private readonly stock: Stock) {} available() { return this.stock.count(); }}@Module({providers:[InventoryService,{provide:STOCK,useValue:{count:()=>4}}],exports:[InventoryService]})export class InventoryModule {}Expected behavior (not observed): Partial module: resolving InventoryService in an initialized Nest context should return 4 from available(). A test may replace STOCK with a controlled value.
How it works
A token may be a class, string or symbol. Interfaces disappear at runtime, so use an explicit token for an interface dependency. The default provider lifetime is singleton within the application context; request scope creates instances for each request and can propagate scope to dependents. Transient providers are instantiated per consuming provider. Choose scope for ownership, not to hide global mutable state.
Practice the underlying idea without dependencies
class Inventory {constructor(stock){this.stock=stock;} available(){return this.stock.count();}}const first=new Inventory({count:()=>4}); const second=new Inventory({count:()=>0});console.log(first.available(),second.available());Run node main.mjs in a disposable directory. Expected output:
4 0This tests the illustrated JavaScript behavior only, not the framework.
Common mistake
Storing a current user on a singleton provider leaks state across requests. Pass the principal explicitly or use carefully chosen scoped dependencies. Do not treat request scope as an authorization control.
Apply it yourself
Explain which token and lifetime you would choose for a read-only configuration object and for per-request context.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dependency injection and scopes — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
Why use a symbol with @Inject for a TypeScript interface?
What is the default provider scope?
Where should request-specific identity be kept?