11 · 실전 아키텍처
DDD와 클린 아키텍처
핵심 비즈니스 규칙이 지금 당장 쓰는 SQL 드라이버나 이메일 벤더, HTTP 프레임워크보다 훨씬 오래 살아남아야 하는 프로젝트라면 DDD / 클린(헥사고날) 아키텍처로 외부 인프라 세부 사항을 코어 모델 바깥으로 밀어내는 게 좋아요. dn-ioc에서는 의존성을 역전시키기 위해 추상 베이스 클래스나 복잡한 컨테이너 모듈을 만들 필요가 없어요. 가장 안쪽 domain/이 인터페이스와 token() 포트를 선언하고, application/이 provide()로 유스케이스를 엮고, infra/가 실제 어댑터들을 단일 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 같은 엔티티와 함께 바깥세상이 충족해야 할 포트(Port)들 — 영속성(OrderRepository)은 물론 현재 시각(Clock)이나 이메일 발송(Mailer) 같은 횡단 관심사 부수 효과까지 — 을 정의하죠.
각 포트는 TypeScript interface와 그 인터페이스 이름을 그대로 딴 token<T>('Name') 한 쌍으로 구성돼요. 예를 들어 Clock을 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하도록 설계된 코드이기 때문이에요. 이미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를 주입받아 쓸 뿐,domain/과application/은sqlTableRef의 존재조차 몰라요. - 계층 전체를
infraProviders하나로 묶으세요:infra/providers.ts는 루트 스코프의 모든 어댑터가 단일 클라이언트를 공유하도록sqlTableRef를 넣고, 모든provideFor()바인딩을 더해 하나의bundleProviders(...)핸들로 묶어 내보내요. - 새 어댑터 추가는 딱 두 군데만 고치면 끝나요: 새로운 인프라 어댑터를 추가할 때는
infra/안에서provideFor()바인딩을 작성하고infraProviders에 한 줄만 추가하면 돼요. 어떤 진입점 파일도 수정할 필요가 없어요.
- 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는 코드베이스에서 유일하게 application/과 infra/ 양쪽을 모두 import해서 providers: [infraProviders]로 딱 맞물려 주는 조합 루트(Composition Root) 역할을 해요.
infraProviders가 재사용 가능한 값으로 묶여 있고 orderServiceRef도 전송 계층 코드와 분리되어 있기 때문에, 같은 도메인 위에 여러 진입점을 각각 몇 줄만으로 가볍게 띄울 수 있어요.
- HTTP API 서버 (
main.ts):[infraProviders]를 설치하고bootstrapApp()안에서orderServiceRef를 미리inject()한 뒤 라우터에 넘겨요. 이렇게 해 두면 토큰 바인딩을 하나라도 빼먹었을 때 실제 고객 요청 도중이 아니라await app.start()시점에 즉시 실패해요. - 큐 워커나 CLI 배치 작업 (
worker.ts): 자체 진입점에서bootstrapApp(..., { providers: [infraProviders] })를 호출하고 똑같은orderServiceRef를 주입받아요. 고객에게 실제 메일을 보내면 안 되는 백필 스크립트라면infraProviders뒤에provideFor(mailerToken, dryRunMailer)한 줄만 덧붙여 덮어쓰면 돼요. - 단위 테스트 (
application/order-service.test.ts):infraProviders는 아예 건너뛰고 가벼운provideFor()가짜 구현만 설치해요. 포트 대역을 단 하나라도 빠뜨리면unitTestApp.start()가 즉시No provider for token: Mailer에러로 알려 줘요.
- 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/ | — |
이제 테스트와 대역 갈아끼우기로 넘어가서 단위 테스트와 통합 테스트 패턴을 나란히 비교해 볼게요.