TheoKit DI — 의존성 주입은(는) 무엇을 하나요?
@theokit/di — 데코레이터 메타데이터를 사용하는 TypeScript DI 컨테이너 빠른 참조입니다.
설치
pnpm add @theokit/di reflect-metadata
reflect-metadata 폴리필이 필요하며, 앱 진입점에서 한 번 임포트해야 합니다. 또한 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)을 사용합니다. 생성자 매개변수 타입은 reflect-metadata를 통해 자동 해석됩니다(매개변수가 클래스인 경우).
@Optional
import { Optional } from "@theokit/di";
@Injectable()
class NotificationService {
constructor(
@Optional() private readonly sms?: SmsGateway,
) {}
}
의존성이 등록되지 않은 경우 TokenNotFoundError를 던지는 대신 undefined로 해석됩니다.
@Qualifier
import { Qualifier } from "@theokit/di";
@Injectable()
class PaymentService {
constructor(
@Qualifier("stripe") private readonly gateway: PaymentGateway,
) {}
}
동일한 인터페이스 토큰으로 등록된 여러 프로바이더를 구분합니다.
@Primary
import { Primary, Injectable } from "@theokit/di";
@Injectable()
@Primary()
class StripeGateway implements PaymentGateway { /* ... */ }
동일한 토큰에 대해 여러 프로바이더가 등록된 경우 기본값으로 표시합니다. @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 | 매 resolve 시 새 인스턴스 |
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[] | 임포트하는 모듈에 표시될 토큰 |
오류
| 오류 | 원인 |
|---|---|
TokenNotFoundError | 토큰이 등록되지 않았고 @Optional도 아님 |
CyclicDependencyError | 해석 그래프에서 순환 의존성 감지 |
MissingInjectableError | @Injectable 없이 의존성으로 사용된 클래스 |
ScopeViolationError | 싱글톤이 transient/request-scoped 의존성에 의존함 |
ContainerDisposedError | container.dispose() 후에 resolve 호출 |
ContainerFrozenError | 컨테이너가 동결된 후에 register 호출 |
AsyncProviderInSyncResolveError | 비동기 팩토리가 resolveAsync() 대신 resolve()와 함께 사용됨 |
ReflectMetadataMissingError | reflect-metadata 폴리필이 임포트되지 않음 |
CyclicModuleImportError | 순환 모듈 임포트 감지 |
InvalidModuleError | 모듈 클래스에 @Module 데코레이터 누락 |
InvalidExportError | 모듈이 자체 프로바이더에 없는 토큰을 내보냄 |
그래프 분석
const graph: DependencyGraph = container.analyzeGraph();
// 의존성 체인 디버깅 및 문제 감지에 유용합니다