TheoKit DI -- 依賴注入 是做什麼的?
@theokit/di 的快速參考——一個具有裝飾器元資料的 TypeScript 依賴注入容器。
安裝
pnpm add @theokit/di reflect-metadata
需要在應用程式入口處匯入一次 reflect-metadata polyfill,並在 tsconfig.json 中啟用 experimentalDecorators 和 emitDecoratorMetadata。
核心裝飾器
@Injectable
import { Injectable, Scope } from "@theokit/di";
@Injectable()
class UserRepository {
findById(id: string) { /* ... */ }
}
// 附帶選項:
@Injectable({ scope: Scope.REQUEST })
class RequestScopedService { /* ... */ }
InjectableOptions:
| 選項 | 類型 | 預設值 | 描述 |
|---|---|---|---|
scope | Scope | Scope.SINGLETON | 生命週期範圍。 |
@Inject
import { Inject } from "@theokit/di";
@Injectable()
class OrderService {
constructor(
@Inject("DATABASE_URL") private readonly dbUrl: string,
private readonly repo: UserRepository, // 由類型自動解析
) {}
}
使用 @Inject(token) 處理字串/符號 token。當參數為類別時,建構子參數類型會透過 reflect-metadata 自動解析。
@Optional
import { Optional } from "@theokit/di";
@Injectable()
class NotificationService {
constructor(
@Optional() private readonly sms?: SmsGateway,
) {}
}
當相依項未註冊時,解析為 undefined 而非擲出 TokenNotFoundError。
@Qualifier
import { Qualifier } from "@theokit/di";
@Injectable()
class PaymentService {
constructor(
@Qualifier("stripe") private readonly gateway: PaymentGateway,
) {}
}
在同一個介面 token 下註冊多個提供者時進行消歧義。
@Primary
import { Primary, Injectable } from "@theokit/di";
@Injectable()
@Primary()
class StripeGateway implements PaymentGateway { /* ... */ }
在為同一個 token 註冊多個提供者時,將提供者標記為預設。除非使用了 @Qualifier,否則勝過非 primary 的提供者。
@PostConstruct / @PreDestroy
import { PostConstruct, PreDestroy, Injectable } from "@theokit/di";
@Injectable()
class DatabasePool {
@PostConstruct()
async init() { /* 在構造後調用 */ }
@PreDestroy()
async shutdown() { /* 在 container.dispose() 時調用 */ }
}
容器
import { Container } from "@theokit/di";
const container = new Container();
// 註冊類別
container.register(UserRepository);
container.register(OrderService);
// 註冊值提供者
container.register("DATABASE_URL", { useValue: "postgres://..." });
// 註冊工廠提供者
container.register("Logger", {
useFactory: (ctx) => new Logger(ctx.resolve("DATABASE_URL")),
});
// 註冊現有別名
container.register("PrimaryRepo", { useExisting: UserRepository });
// 解析
const service = container.resolve(OrderService);
const asyncService = await container.resolveAsync(OrderService);
// 釋放(調用 @PreDestroy 鉤子)
await container.dispose();
ContainerOptions
interface ContainerOptions {
parent?: Container; // 階層式容器
autoRegister?: boolean; // 預設 false
}
提供者類型
type Provider =
| ClassProvider // { useClass: Constructor, scope? }
| ValueProvider // { useValue: any }
| FactoryProvider // { useFactory: (ctx) => any, scope? }
| ExistingProvider; // { useExisting: Token }
作用域
import { Scope } from "@theokit/di";
| 作用域 | 行為 |
|---|---|
Scope.SINGLETON | 每個容器一個實例(預設)。 |
Scope.TRANSIENT | 每次解析建立新實例。 |
Scope.REQUEST | 每個請求作用域一個實例(透過 container.createScope())。 |
請求作用域範例:
const requestContainer = container.createScope();
const handler = requestContainer.resolve(RequestHandler);
// 所有 REQUEST 作用域的相依項在此作用域內共享同一個實例
@Module
import { Module } from "@theokit/di";
@Module({
providers: [UserRepository, OrderService],
imports: [DatabaseModule],
exports: [UserRepository],
})
class UserModule {}
// 將模組載入容器
container.loadModule(UserModule);
ModuleMetadata:
| 欄位 | 類型 | 描述 |
|---|---|---|
providers | Provider[] | 在此模組中註冊的類別/提供者。 |
imports | Module[] | 其他匯出的模組可供使用。 |
exports | Token[] | 對匯入模組可見的 token。 |
錯誤
| 錯誤 | 原因 |
|---|---|
TokenNotFoundError | Token 未註冊且非 @Optional。 |
CyclicDependencyError | 解析圖中偵測到循環依賴。 |
MissingInjectableError | 類別作為依賴使用但缺少 @Injectable。 |
ScopeViolationError | Singleton 依賴於 transient 或 request-scoped 的依賴項。 |
ContainerDisposedError | 在 container.dispose() 後調用 resolve。 |
ContainerFrozenError | 容器凍結後調用 register。 |
AsyncProviderInSyncResolveError | 非同步工廠與 resolve() 一起使用,應使用 resolveAsync()。 |
ReflectMetadataMissingError | 未匯入 reflect-metadata polyfill。 |
CyclicModuleImportError | 偵測到循環模組匯入。 |
InvalidModuleError | 模組類別缺少 @Module 裝飾器。 |
InvalidExportError | 模組匯出一個不在其提供者中的 token。 |
圖形分析
const graph: DependencyGraph = container.analyzeGraph();
// 適用於除錯依賴鏈和偵測問題