Communityライティング&編集github.com

TheoKit DI -- 依存性注入

Decoratorメタデータを使用するTypeScript DIコンテナ「@theokit/di」のクイックリファレンス。

TheoKit DI -- 依存性注入 とは?

このスキルは、TypeScriptプロジェクト向けのDI(依存性注入)コンテナライブラリ「@theokit/di」の完全なリファレンスを提供します。開発者が正確で効率的な依存性注入コードを記述できるように、主要なDecorator(@Injectable, @Inject, @Optional, @Qualifier, @Primary, @PostConstruct, @PreDestroy)、コンテナの操作(register, resolve, dispose)、スコープ(SINGLETON, TRANSIENT, REQUEST)、モジュールシステム、エラーハンドリングについて詳しく説明しています。`reflect-metadata`ポリフィルと`experimentalDecorators`、`emitDecoratorMetadata`の設定が必要で、CLI操作や環境変数名はそのまま保持されます。このスキルはClaude CodeなどのAIエージェント上で動作し、開発者がプラグインやアプリケーションの依存関係管理を正確に行えるよう支援します。

対応✓Claude Code~Codex CLI~Cursor
npx skills add usetheokit/theokit-skills

Installed? Explore more ライティング&編集 skills: steipete/notion, langchain-ai/langchain, bytedance/podcast-generation · View all 6 →

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

TheoKit DI -- 依存性注入 は何をしますか?

@theokit/di -- Decoratorメタデータを使用するTypeScript DIコンテナのクイックリファレンス。

インストール

pnpm add @theokit/di reflect-metadata

アプリケーションエントリで一度だけインポートするreflect-metadataポリフィルと、tsconfig.jsonのexperimentalDecorators + emitDecoratorMetadataが必要です。

コアDecorator

@Injectable

import { Injectable, Scope } from "@theokit/di";

@Injectable()
class UserRepository {
  findById(id: string) { /* ... */ }
}

// オプション付き:
@Injectable({ scope: Scope.REQUEST })
class RequestScopedService { /* ... */ }

InjectableOptions:

オプション型デフォルト説明
scopeScopeScope.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コンテナごとに1つのインスタンス(デフォルト)。
Scope.TRANSIENT解決のたびに新しいインスタンス。
Scope.REQUESTリクエストスコープごとに1つのインスタンス(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:

フィールド型説明
providersProvider[]このモジュールに登録されるクラス/プロバイダ。
importsModule[]エクスポートが利用可能になる他のモジュール。
exportsToken[]インポートするモジュールから見えるトークン。

エラー

エラー原因
TokenNotFoundErrorトークンが登録されておらず、@Optionalでもない。
CyclicDependencyError解決グラフで循環依存が検出された。
MissingInjectableError@Injectableなしで依存関係として使用されたクラス。
ScopeViolationErrorSingletonがTransient/Requestスコープの依存関係に依存している。
ContainerDisposedErrorcontainer.dispose()の後に解決が呼び出された。
ContainerFrozenErrorコンテナがフリーズした後に登録が呼び出された。
AsyncProviderInSyncResolveError非同期ファクトリがresolveAsync()ではなくresolve()で使用された。
ReflectMetadataMissingErrorreflect-metadataポリフィルがインポートされていない。
CyclicModuleImportError循環モジュールインポートが検出された。
InvalidModuleErrorモジュールクラスに@ModuleDecoratorがない。
InvalidExportErrorモジュールがそのプロバイダにないトークンをエクスポートしている。

グラフ分析

const graph: DependencyGraph = container.analyzeGraph();
// 依存関係チェーンのデバッグや問題の検出に便利

関連スキル