11 · 実践アーキテクチャ
DDD とクリーンアーキテクチャ
現在の SQL ドライバやメール配信サービス、HTTP フレームワークよりもビジネスルールの寿命のほうが長いプロジェクトでは、DDD / クリーンアーキテクチャ(ヘキサゴナルアーキテクチャ) で外部インフラの都合をコアモデルの外へ追い出すのが効果的です。dn-ioc で依存性逆転をやるのに、抽象基底クラスも大仰なコンテナモジュールもいりません。一番内側の domain/ でインターフェースと token() ポートを宣言し、application/ で provide() を使ってユースケースを組み立て、infra/ で本物のアダプタ群を1つの bundleProviders() にまとめて公開するだけです。
1src/2├── domain/ # プロジェクト内の他レイヤーを一切 import しない3│ ├── order.ts # Order エンティティ + OrderRepository ポートと token4│ └── ports.ts # 横断的な Clock・Mailer ポートと token5├── application/ # domain/ のみ import 可6│ ├── order-service.ts # ドメイン token を注入する OrderService ユースケース Ref7│ └── order-service.test.ts # 軽量なフェイクだけをバインドする純粋な単体テスト8├── infra/ # domain/ のみ import 可9│ ├── sql-order-repository.ts # 非公開の sqlTableRef + sqlOrderRepositoryProvider10│ ├── system-adapters.ts # systemClockProvider + smtpMailerProvider11│ └── providers.ts # infraProviders = bundleProviders(...)12└── main.ts # Composition Root:application/ と infra/ を統合
1. 純粋なドメインエンティティとポート Token(domain/)
domain/ ディレクトリは依存グラフのど真ん中に位置し、プロジェクト内の ほかのどのレイヤーも import しません。Order のようなエンティティと並べて、永続化(OrderRepository)や現在時刻(Clock)、メール送信(Mailer)といった「外の世界が満たすべき ポート(Port)」を定義します。
各ポートは、TypeScript の interface と、そのインターフェース名をそのまま付けた token<T>('Name') のペアで書きます。たとえば現在時刻の取得を clockToken の裏に隠しておけば、ビジネスルールの中で直接 new Date() を呼ばずに済むため、時刻が絡む状態遷移のテストが 100% 決定論的になります。
- domain/
1import { token } from 'dn-ioc'23export interface Order {4 id: string5 customerEmail: string6 status: 'draft' | 'submitted'7 submittedAt?: Date8}910export interface OrderRepository {11 find(id: string): Promise<Order | undefined>12 save(order: Order): Promise<void>13}1415export const orderRepositoryToken = token<OrderRepository>('OrderRepository')
1import { token } from 'dn-ioc'23export interface Clock {4 now(): Date5}67export interface Mailer {8 sendOrderConfirmation(email: string, orderId: string): Promise<void>9}1011export const clockToken = token<Clock>('Clock')12export const mailerToken = token<Mailer>('Mailer')
2. アプリケーション層のユースケース(application/)
application/ レイヤーは、ドメインエンティティとポートを組み合わせて OrderService.submit(id) のようなユースケースを実行します。ここで意図的にハイブリッドな使い分けをしている点に注目してください。
OrderServiceが外部の機能を呼び出すときは、すべて ドメイントークン(orderRepositoryToken、clockToken、mailerToken)経由で注入します。注文データが Postgres にあるのか SQLite にあるのか、それともオンメモリのMapにあるのかは一切知りません。- なのに、
orderServiceRef自身はprovide(({ inject }) => { ... })で作ったRefとしてエクスポートしています! なぜかというと、application/を呼ぶ側(HTTP コントローラ、CLI コマンド、キューワーカー、テスト)はいずれも 外側のレイヤー にあり、ユースケースを直接 import するのが本来あるべき方向だからです。すでに矢印が内側を向いている箇所にまで、冗長なトークンを作る必要はありません。
1import { provide } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'3import { clockToken, mailerToken } from '../domain/ports'45export const orderServiceRef = provide(({ inject }) => {6 const orders = inject(orderRepositoryToken)7 const clock = inject(clockToken)8 const mailer = inject(mailerToken)910 return {11 async submit(id: string): Promise<Order> {12 const order = await orders.find(id)13 if (!order) {14 throw new Error(`Order ${id} not found`)15 }16 if (order.status === 'submitted') {17 throw new Error(`Order ${id} already submitted`)18 }1920 const submitted: Order = {21 ...order,22 status: 'submitted',23 submittedAt: clock.now(),24 }2526 await orders.save(submitted)27 await mailer.sendOrderConfirmation(submitted.customerEmail, submitted.id)28 return submitted29 },30 }31})
3. インフラ層のアダプタとバンドル(infra/)
infra/ ディレクトリは domain/ の契約を import し、実際のドライバや SDK、データベースを使って実装を与えます。
- ドライバのハンドルは
infra/内部に隠す:sql-order-repository.tsのsqlTableRefは、テーブルや接続プールの状態を保持してonDisposeフックを登録する非公開のRefです。sqlOrderRepositoryProviderは裏側でこのsqlTableRefをinject()しますが、domain/とapplication/はsqlTableRefの存在すら知りません。 - インフラ層まるごと
infraProvidersに束ねる:infra/providers.tsでは、sqlTableRef(ルートスコープ内の全アダプタで同じクライアントを共有するため)と各provideFor()バインドを1つのbundleProviders(...)ハンドルにまとめています。 - 新しいアダプタの追加は2箇所触るだけ: 新しいインフラアダプタが増えても、
infra/の中でprovideFor()を書き、infraProvidersに1行足すだけです。どのエントリポイントも書き換える必要がありません。
- infra/
1import { provide, provideFor } from 'dn-ioc'2import { type Order, orderRepositoryToken } from '../domain/order'34// Private infrastructure client — never imported by domain or application5export const sqlTableRef = provide(({ onDispose }) => {6 const rows = new Map<string, Order>([['ord-1', { id: 'ord-1', customerEmail: 'ada@example.com', status: 'draft' }]])7 onDispose(() => {8 rows.clear()9 })10 return rows11})1213export const sqlOrderRepositoryProvider = provideFor(orderRepositoryToken, ({ inject }) => {14 const rows = inject(sqlTableRef)15 return {16 find: async id => rows.get(id),17 save: async order => {18 rows.set(order.id, order)19 },20 }21})
1import { provideFor } from 'dn-ioc'2import { clockToken, type Mailer, mailerToken } from '../domain/ports'34const smtpMailer: Mailer = {5 async sendOrderConfirmation(email, orderId) {6 // Stands in for an SMTP or transactional email HTTP client7 void email8 void orderId9 },10}1112export const systemClockProvider = provideFor(clockToken, () => ({ now: () => new Date() }))13export const smtpMailerProvider = provideFor(mailerToken, () => smtpMailer)
1import { bundleProviders } from 'dn-ioc'2import { sqlOrderRepositoryProvider, sqlTableRef } from './sql-order-repository'3import { smtpMailerProvider, systemClockProvider } from './system-adapters'45// One bundle collects every infrastructure adapter; entrypoints install it once6export const infraProviders = bundleProviders(7 sqlTableRef,8 sqlOrderRepositoryProvider,9 systemClockProvider,10 smtpMailerProvider,11)
4. Composition Root と複数エントリポイントでの再利用
main.ts は Composition Root(合成起点)、つまりコードベース全体で唯一 application/ と infra/ の両方を import して providers: [infraProviders] でガチャンと組み合わせる場所です。
infraProviders が再利用可能なバンドルになっていて、orderServiceRef も通信プロトコルから切り離されているため、同じドメインの上に複数のエントリポイントを数行ずつで立ち上げられます。
- HTTP API サーバー (
main.ts):[infraProviders]を登録し、bootstrapApp()の中でorderServiceRefをinject()してルーターへ渡します。起動時に解決させておくことで、万一トークンのバインド漏れがあっても本番リクエストの途中ではなくawait app.start()の瞬間に即失敗させられます。 - キューワーカーや CLI バッチ (
worker.ts): 別ファイルのエントリポイントでbootstrapApp(..., { providers: [infraProviders] })を呼び、まったく同じorderServiceRefを使います。顧客にメールを飛ばしたくないデータ移行スクリプトなら、infraProvidersの 後ろ にprovideFor(mailerToken, dryRunMailer)を1つ添えるだけで上書き完了です。 - 単体テスト (
application/order-service.test.ts):infraProvidersは一切読み込まず、軽量なprovideFor()のフェイクだけを登録します。もしポートのフェイクを1つでも渡し忘れれば、unitTestApp.start()が即座にNo provider for token: Mailerで reject してくれます。
- application/
1import { bootstrapApp } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { infraProviders } from './infra/providers'45// Composition Root: the only module that imports both application and infra6export const app = bootstrapApp(7 async ({ inject }) => {8 const orders = inject(orderServiceRef)9 const submitted = await orders.submit('ord-1')10 console.log(submitted.status) // submitted11 },12 {13 providers: [infraProviders],14 },15)1617await app.start()18await app.stop()
1import { bootstrapApp, provideFor } from 'dn-ioc'2import { orderServiceRef } from './application/order-service'3import { type Order, type OrderRepository, orderRepositoryToken } from './domain/order'4import { clockToken, type Mailer, mailerToken } from './domain/ports'56const saved: Order[] = []7const sentEmails: string[] = []8const fixedNow = new Date('2026-11-18T12:00:00.000Z')910const fakeOrderRepository = (): OrderRepository => ({11 find: async id => ({ id, customerEmail: 'ada@example.com', status: 'draft' }),12 save: async order => {13 saved.push(order)14 },15})1617const fakeMailer = (): Mailer => ({18 sendOrderConfirmation: async (email, orderId) => {19 sentEmails.push(`${email}:${orderId}`)20 },21})2223export const unitTestApp = bootstrapApp(24 async ({ inject }) => {25 const result = await inject(orderServiceRef).submit('ord-42')26 console.log(result.status, saved.length, sentEmails) // submitted 1 [ 'ada@example.com:ord-42' ]27 },28 {29 // Pure fakes only — forgetting any token fails fast with "No provider for token: <Name>"30 providers: [31 provideFor(orderRepositoryToken, fakeOrderRepository),32 provideFor(clockToken, () => ({ now: () => fixedNow })),33 provideFor(mailerToken, fakeMailer),34 ],35 },36)3738await unitTestApp.start()39await unitTestApp.stop()
5. レイヤー間の import 境界まとめ
dn-ioc が扱うのは実行時のハンドルだけで、静的な import 文までは監視しません。各ディレクトリ間の依存方向は次のルールを目安に保ちましょう。
| レイヤー | 許可するプロジェクト内 import | 禁止するプロジェクト内 import |
|---|---|---|
domain/ | なし('dn-ioc' の token のみ) | application/, infra/, main.ts |
application/ | domain/ | infra/, main.ts |
infra/ | domain/ | application/, main.ts |
main.ts(エントリポイント) | application/, infra/, domain/ | — |
続いて、テストとモック差し替え で単体テストと結合テストの実践パターンを並べて見ていきましょう。