dn-ioc

11 · Engineering Patterns

DDD & Clean Architecture

When business rules outlive your current SQL driver, email vendor, or HTTP framework, DDD / Clean (Hexagonal) Architecture keeps external plumbing out of your core model. In dn-ioc, you don't need abstract base classes or container modules to invert dependencies: your inner domain/ declares interfaces and token() ports, application/ orchestrates use cases with provide(), and infra/ binds real adapters into a single bundleProviders() export.

ddd-project
1src/2├── domain/                        # Imports NO other project layer3│   ├── order.ts                   # Order entity + OrderRepository port & token4│   └── ports.ts                   # Cross-cutting Clock & Mailer ports & tokens5├── application/                   # Imports domain/ only6│   ├── order-service.ts           # OrderService use-case Ref injecting domain tokens7│   └── order-service.test.ts      # Pure unit test binding lightweight fakes8├── infra/                         # Imports domain/ only9│   ├── sql-order-repository.ts    # Private sqlTableRef + sqlOrderRepositoryProvider10│   ├── system-adapters.ts         # systemClockProvider + smtpMailerProvider11│   └── providers.ts               # infraProviders = bundleProviders(...)12└── main.ts                        # Composition Root: imports application/ + infra/

1. Pure Domain Entities & Port Tokens (domain/)

Your domain/ folder sits at the center of the graph and imports zero other layers in your project. Alongside entities like Order, it defines the ports the outside world must satisfy—both persistence (OrderRepository) and cross-cutting side effects like system time (Clock) and email (Mailer).

Each port pairs a TypeScript interface with a token<T>('Name') named directly after that interface. Putting Clock behind clockToken means business rules never call new Date() directly, so time-sensitive transitions stay 100% deterministic in tests.

domain/order.ts
  • 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 Use Cases (application/)

The application/ layer coordinates domain entities and ports to fulfill a use case like OrderService.submit(id). Notice an intentional hybrid here:

  • OrderService pulls in external capabilities exclusively through domain tokens (orderRepositoryToken, clockToken, mailerToken)—it has no idea whether orders live in Postgres, SQLite, or a Map.
  • Yet orderServiceRef itself is exported as a Ref via provide(({ inject }) => { ... })! Why? Because callers of application/—HTTP controllers, CLI commands, queue workers, and tests—live in outer layers that are supposed to import use cases directly. You don't need redundant tokens for services whose import arrow already points inward.
application/order-service.ts
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. Infrastructure Adapters & Bundle (infra/)

The infra/ folder imports domain/ contracts and implements them against real drivers, SDKs, and databases:

  • Keep driver handles private to infra/: In sql-order-repository.ts, sqlTableRef is an internal Ref that owns the underlying table/pool state and registers an onDispose hook. sqlOrderRepositoryProvider injects sqlTableRef behind the scenes, while domain/ and application/ never know sqlTableRef exists.
  • Pack the whole layer into infraProviders: infra/providers.ts collects sqlTableRef (so every adapter in the root scope shares one underlying client) plus every provideFor() binding into a single bundleProviders(...) handle.
  • Two-edit rule for new adapters: Adding a new infrastructure adapter takes just two edits inside infra/—write its provideFor() binding and add one line to infraProviders. None of your entrypoints have to change.
infra/sql-order-repository.ts
  • 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 & Multi-Entrypoint Reuse

main.ts is the Composition Root—the single place in the codebase that imports both application/ and infra/ and snaps them together with providers: [infraProviders].

Because infraProviders is a reusable value and orderServiceRef is decoupled from transport code, spinning up multiple entrypoints over the same domain takes a handful of lines each:

  • HTTP API server (main.ts): Installs [infraProviders], injects orderServiceRef inside bootstrapApp() (so any missing token binding fails immediately on await app.start(), not halfway through a live customer request), and hands it to your router.
  • Queue worker or CLI job (worker.ts): Calls bootstrapApp(..., { providers: [infraProviders] }) in its own entrypoint and injects the exact same orderServiceRef—or tucks a provideFor(mailerToken, dryRunMailer) after infraProviders for a backfill script that shouldn't email customers.
  • Unit test (application/order-service.test.ts): Skips infraProviders altogether and installs lightweight provideFor() fakes. Forgetting even one port fake immediately rejects unitTestApp.start() with No provider for token: Mailer.
main.ts
  • 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. Layer Import Boundaries

Because dn-ioc only sees runtime handles, keep these static import directions in mind across your project folders:

LayerAllowed project importsForbidden project imports
domain/None ('dn-ioc' token only)application/, infra/, main.ts
application/domain/infra/, main.ts
infra/domain/application/, main.ts
main.ts (Entrypoints)application/, infra/, domain/—

Now let's put both unit and integration testing patterns side by side in Testing & Mocking.