NestJS Dependency Injection: IoC in Depth

NestJS Dependency Injection: IoC in Depth

A comprehensive architectural guide to NestJS Dependency Injection and the Inversion of Control (IoC) container. Master custom providers, injection tokens, provider lifecycles, and circular dependency resolution.

NestJSTypeScriptDependency InjectionBackend

Why Manual Object Wiring Breaks in Large Backends

Node.js နဲ့ TypeScript သုံးပြီး Enterprise Backend Application တစ်ခု တည်ဆောက်တဲ့အခါ Controllers, Services, Repositories နဲ့ External SDK Clients တွေ ရာနဲ့ချီပြီး ရှိလာတတ်ပါတယ်။ အကယ်၍ OrderController ထဲမှာ new OrderService(new PrismaClient(), new StripeClient(), new RedisCache()) ဆိုပြီး Dependencies တွေကို ကိုယ်တိုင် new Keyword နဲ့ တိုက်ရိုက် တည်ဆောက်နေမယ်ဆိုရင် Tight Coupling ပြဿနာ စတင်ကြုံတွေ့ရပါတယ်။

ဒီလို Manual Wiring ပုံစံမှာ Database Connection Pool တစ်ခုတည်းကို မျှဝေသုံးစွဲဖို့ ခက်ခဲသလို၊ Unit Testing ရေးသားတဲ့အခါမှာလည်း တကယ့် Stripe API သို့မဟုတ် Production Database ကို Mock Object နဲ့ အစားထိုးဖို့ မဖြစ်နိုင်သလောက် ခက်ခဲသွားပါတယ်။ Inversion of Control (IoC) ဆိုတာကတော့ Object ဖန်တီးခြင်းနဲ့ ချိတ်ဆက်ပေးခြင်း တာဝန်ကို Application Code ဆီကနေ NestJS IoC Container ဆီသို့ လွှဲပြောင်းပေးလိုက်တဲ့ Architectural Pattern ပဲ ဖြစ်ပါတယ်။

How the NestJS IoC Container Works Under the Hood

NestJS Application တစ်ခု စတင် Run (NestFactory.create(AppModule)) လိုက်တဲ့အခါ IoC Container ဟာ အဆင့် ၃ ဆင့်နဲ့ Dependency Graph တစ်ခုလုံးကို တည်ဆောက်ပေးပါတယ်။

  1. Metadata Reflection: TypeScript Compiler ရဲ့ emitDecoratorMetadata နဲ့ reflect-metadata တို့ကို အသုံးပြုပြီး @Injectable() နဲ့ @Controller() Classes တွေရဲ့ Constructor Parameters တွေက ဘယ် Type တွေလဲဆိုတာ စစ်ဆေးဖတ်ယူပါတယ်။
  2. Dependency Graph Resolution: Module တစ်ခုချင်းစီရဲ့ imports, providers နဲ့ exports Boundaries တွေကို စစ်ဆေးပြီး အောက်ခြေ Leaf Dependencies (ဥပမာ ConfigService, PrismaService) ကနေ အပေါ်ဆုံး Controllers အထိ Topological Sort ပုံစံနဲ့ အစီအစဉ် ဆွဲပေးပါတယ်။
  3. Instantiation & Caching: သတ်မှတ်ထားတဲ့ Scope အလိုက် Providers တွေကို Instantiate လုပ်ပြီး Container Memory ထဲမှာ Singleton Cache အနေနဲ့ သိမ်းဆည်းပေးထားပါတယ်။
Loading flowchart...

Beyond @Injectable(): Custom Providers and Injection Tokens

သာမန် Class တစ်ခုကို @Injectable() တပ်ပေးရုံနဲ့ Standard Class Provider အဖြစ် အလုပ်လုပ်ပေမဲ့၊ TypeScript Interfaces တွေဟာ Compile လုပ်ပြီးချိန်မှာ JavaScript Runtime မှာ ပျောက်ကွယ်သွားတဲ့အတွက် Interface ကို တိုက်ရိုက် Inject လုပ်လို့ မရပါဘူး။ ဒီအတွက် Custom Injection Tokens (Symbol သို့မဟုတ် String) နဲ့ Custom Providers ၄ မျိုးကို အသုံးပြုရပါတယ်။

  • useClass: Environment သို့မဟုတ် Condition အလိုက် မတူညီတဲ့ Implementation Class ကို ပြောင်းလဲပေးချင်တဲ့အခါ သုံးပါတယ် (ဥပမာ Production မှာ S3StorageService နဲ့ Local မှာ DiskStorageService)။
  • useValue: ပြင်ပ Configuration Objects၊ Constants သို့မဟုတ် Unit Test ထဲက Mock Objects တွေကို တိုက်ရိုက် ထည့်သွင်းပေးချင်တဲ့အခါ သုံးပါတယ်။
  • useFactory: အခြား Service တစ်ခု (ConfigService) ရဲ့ တန်ဖိုးအပေါ် မူတည်ပြီး Dynamic အနေနဲ့ ဖန်တီးရမယ့် Providers တွေ သို့မဟုတ် async/await နဲ့ ချိတ်ဆက်ရမယ့် Database/SDK Connections တွေအတွက် သုံးပါတယ်။
  • useExisting: ရှိပြီးသား Provider တစ်ခုကို အခြား Token အမည်အသစ် (Alias) တစ်ခုနဲ့ ညွှန်းဆိုချင်တဲ့အခါ သုံးပါတယ်။
export const PAYMENT_GATEWAY = Symbol('PAYMENT_GATEWAY')

export interface PaymentGateway {
  charge(amount: number): Promise<boolean>
}

@Injectable()
export class OrderService {
  constructor(@Inject(PAYMENT_GATEWAY) private readonly gateway: PaymentGateway) {}
}

@Module({
  providers: [
    OrderService,
    {
      provide: PAYMENT_GATEWAY,
      inject: [ConfigService],
      useFactory: async (config: ConfigService): Promise<PaymentGateway> => {
        const apiKey = config.getOrThrow<string>('STRIPE_API_KEY')
        return new StripeGatewayClient(apiKey)
      },
    },
  ],
})
export class OrderModule {}

အထက်ပါ ပုံစံမှာ OrderService ဟာ StripeGatewayClient ဆိုတဲ့ Concrete Class ကို လုံးဝ သိရှိစရာမလိုဘဲ PAYMENT_GATEWAY Token နဲ့ PaymentGateway Interface အပေါ်မှာသာ မှီခိုထားတဲ့အတွက် Dependency Inversion Principle (DIP) ကို အပြည့်အဝ လိုက်နာပြီးသား ဖြစ်သွားပါတယ်။ ဒါ့အပြင် Reusable Library Module တွေ တည်ဆောက်တဲ့အခါမှာလည်း NestJS ရဲ့ ConfigurableModuleBuilder ကို အသုံးပြုပြီး forRoot(), forRootAsync() နဲ့ registerAsync() Methods တွေကို Type-Safe ဖြစ်စွာ အလိုအလျောက် တည်ဆောက်ပေးနိုင်တဲ့အတွက် Boilerplate Code အမြောက်အမြားကို လျှော့ချနိုင်ပါတယ်။

Provider Scopes: Singleton, Request, and Transient

NestJS မှာ Provider တစ်ခုချင်းစီရဲ့ သက်တမ်း (Lifecycle Scope) ကို ၃ မျိုး ရွေးချယ်သတ်မှတ်နိုင်ပါတယ်။

Scope TypeInstantiation TimingMemory & CPU ImpactShared Across RequestsBest Engineering Fit
DEFAULT (Singleton)Once at application bootstrapMinimal (cached in RAM)Yes (1 instance for entire app)Stateless services, repositories, DB pools
Scope.REQUESTNew instance per incoming HTTP requestHigh (GC pressure at scale)No (isolated per request)Multi-tenant context, per-request audit state
Scope.TRANSIENTNew instance for every consumerModerateNo (dedicated instance per parent)Stateful helper utilities, custom loggers

သတိထားရမယ့် အရေးကြီးဆုံး အချက်ကတော့ Scope Hierarchy Bubbling ဖြစ်ပါတယ်။ အကယ်၍ Request-Scoped Service တစ်ခုကို Singleton OrderController ထဲမှာ Inject လုပ်လိုက်မယ်ဆိုရင်၊ အဲဒီ OrderController နဲ့ သူ့အပေါ်က မှီခိုနေတဲ့ Dependency Chain တစ်ခုလုံးဟာလည်း အလိုအလျောက် Request-Scoped အဖြစ် ပြောင်းလဲသွားပါတယ်။ Request တစ်ခုဝင်တိုင်း Controller နဲ့ Service Trees တွေကို အသစ်ပြန်ဆောက်ရပြီး Request ပြီးတိုင်း Garbage Collector က ပြန်ရှင်းရတဲ့အတွက် High-Traffic Endpoints တွေမှာ Throughput 30%–50% အထိ ကျဆင်းသွားနိုင်ပါတယ်။

ဒါကြောင့် Request Context (tenantId, correlationId) ကို လက်ဆင့်ကမ်းချင်တဲ့အခါ Scope.REQUEST အစား Node.js ရဲ့ AsyncLocalStorage (nestjs-cls) ကို သုံးပြီး Providers အားလုံးကို Singleton အဖြစ် ဆက်လက်ထားရှိခြင်းက စွမ်းဆောင်ရည် အမြင့်မားဆုံး နည်းလမ်း ဖြစ်ပါတယ်။

Dynamic Resolution with ModuleRef and Lifecycle Hooks

တချို့သော အခြေအနေတွေမှာ Dependency ကို Constructor ထဲမှာ ကြိုတင် Inject လုပ်ထားလို့ မရဘဲ၊ Runtime ရောက်မှ User ရဲ့ Input သို့မဟုတ် Event Type ပေါ် မူတည်ပြီး သက်ဆိုင်ရာ Provider ကို IoC Container ထဲကနေ လှမ်းယူရတာမျိုး (Strategy Pattern) ရှိတတ်ပါတယ်။ အဲဒီလို အခါမျိုးမှာ NestJS ရဲ့ ModuleRef ကို အသုံးပြုပြီး Container ကို တိုက်ရိုက် Query လုပ်နိုင်ပါတယ်။

ဒါ့အပြင် IoC Container က စီမံခန့်ခွဲနေတဲ့ Providers တွေဟာ OnModuleInit နဲ့ OnApplicationShutdown လိုမျိုး Lifecycle Hooks တွေနဲ့ ချိတ်ဆက်နိုင်ပါတယ်။ Database Connection Pools တွေ၊ Redis Clients တွေနဲ့ Message Queue Consumers တွေကို Application စတက်ချိန်မှာ စနစ်တကျ ချိတ်ဆက်ဖို့နဲ့ SIGTERM ဝင်လာတဲ့အခါ Graceful Shutdown ပြုလုပ်ဖို့အတွက် အလွန် အသုံးဝင်ပါတယ်။

import { Injectable, OnModuleInit, OnApplicationShutdown } from '@nestjs/common'
import { ModuleRef } from '@nestjs/core'

@Injectable()
export class PaymentStrategyResolver implements OnModuleInit, OnApplicationShutdown {
  constructor(private readonly moduleRef: ModuleRef) {}

  async onModuleInit() {
    // Pre-warm or validate registered strategy providers at startup
  }

  resolveGateway(token: symbol) {
    return this.moduleRef.get(token, { strict: false })
  }

  async onApplicationShutdown(signal?: string) {
    // Gracefully flush in-flight payment webhooks before exit
  }
}

Resolving Circular Dependencies and Module Encapsulation

Project ကြီးထွားလာတဲ့အခါ UserService က AuthService ကို ခေါ်ပြီး AuthService ကလည်း UserService ကို ပြန်ခေါ်မိတဲ့ Circular Dependency ပြဿနာ ကြုံတွေ့ရတတ်ပါတယ်။ NestJS မှာ forwardRef(() => AuthService) နဲ့ ယာယီ ဖြေရှင်းနိုင်ပေမဲ့၊ ပိုကောင်းတဲ့ Architectural ဖြေရှင်းနည်းကတော့ နှစ်ဖက်လုံး သုံးချင်တဲ့ တူညီတဲ့ Logic ကို တတိယ Service အသစ် (TokenService သို့မဟုတ် UserIdentityService) အဖြစ် သီးခြားခွဲထုတ်ခြင်း သို့မဟုတ် EventEmitter2 နဲ့ Event-Driven ပုံစံ ပြောင်းလဲခြင်း ဖြစ်ပါတယ်။

ဒါ့အပြင် Module တစ်ခုမှာ @Global() Decorator ကို အလွန်အကျွံ သုံးစွဲခြင်းမှလည်း ရှောင်ရှားသင့်ပါတယ်။ Module Boundary တွေကို ရှင်းလင်းစွာ သတ်မှတ်ပြီး အပြင်ဘက်က သုံးခွင့်ရှိတဲ့ Public Services တွေကိုသာ exports: [...] ထဲမှာ တိကျစွာ ထည့်သွင်းပေးခြင်းအားဖြင့် Architecture တစ်ခုလုံးရဲ့ Encapsulation နဲ့ Unit Testing Isolation ကို ထိန်းသိမ်းထားနိုင်ပါတယ်။ Integration Tests ရေးသားတဲ့အခါမှာလည်း Test.createTestingModule() ရဲ့ .overrideProvider(PAYMENT_GATEWAY).useValue(mockGateway) Method ကို အသုံးပြုပြီး မည်သည့် External Provider ကိုမဆို စက္ကန့်ပိုင်းအတွင်း အလွယ်တကူ အစားထိုး စမ်းသပ်နိုင်ပါတယ်။

Final Thoughts

NestJS Dependency Injection နဲ့ IoC Container ဟာ Decorator အလှဆင်ရုံ သက်သက် မဟုတ်ဘဲ၊ Enterprise Codebase တစ်ခုလုံးကို Loose Coupling ဖြစ်အောင်နဲ့ Testability မြင့်မားအောင် ထိန်းကျောင်းပေးတဲ့ အဓိက အင်ဂျင်ဖြစ်ပါတယ်။ Custom Injection Tokens၊ useFactory Providers၊ ModuleRef တို့ကို မှန်ကန်စွာ အသုံးချပြီး၊ Singleton Scope + AsyncLocalStorage ပုံစံနဲ့ တည်ဆောက်ခြင်းအားဖြင့် စွမ်းဆောင်ရည်မြင့်မားပြီး ရေရှည်ပြုပြင်ထိန်းသိမ်းရ လွယ်ကူတဲ့ Backend Architecture တစ်ခုကို ရရှိနိုင်မှာ ဖြစ်ပါတယ်။