NestJS

Nest custom provider

Dependency injection supplies an object’s dependencies from outside the object. Nest resolves registered provider tokens and manages provider lifetimes. 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. Static example only; runtime NOT RUN. Source: https://docs.nestjs.com/fundamentals/custom-providers.

Formal Syntax & Structure

nodejs syntaxnodejs
{ provide: TOKEN, useValue: implementation }

Working Example

Example Snippetnodejs
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 {}
Node.js Reference