10 · Engineering Patterns
MVC Pattern in Practice
For most HTTP APIs, internal tools, and CRUD backends, classic layered MVC (Controller → Service → Repository → Database) hits the sweet spot. Because each layer is allowed to import the concrete layer directly underneath it, every module in the stack can be a self-providing Ref<T>—giving you clean separation of concerns without maintaining a giant central container file.
1src/2├── models/3│ └── user.ts # Plain TypeScript data shapes (zero runtime code)4├── db/5│ └── database.ts # Stateful connection pool Ref + onDispose teardown6├── repositories/7│ └── user-repository.ts # Data-access Ref injecting databaseRef8├── services/9│ ├── user-service.ts # Business-rule Ref injecting userRepositoryRef10│ └── user-service.test.ts # Unit test swapping userRepositoryRef via provideFor()11├── controllers/12│ └── user-controller.ts # Transport Ref injecting userServiceRef13└── main.ts # Entrypoint registering [databaseRef] at root
Layer-by-Layer Import Rules
In a healthy MVC codebase, imports flow strictly top-down—controllers never skip services to query tables directly, and repositories never import HTTP controllers:
| Layer | File | Exports | Allowed project imports | Responsibility |
|---|---|---|---|---|
| Models | models/user.ts | type User | None | Shared TypeScript interfaces and value shapes. |
| Database | db/database.ts | databaseRef | None | Owns the connection pool and registers onDispose() cleanup. |
| Repositories | repositories/user-repository.ts | userRepositoryRef | db/, models/ | Encapsulates collection/SQL queries behind typed methods. |
| Services | services/user-service.ts | userServiceRef | repositories/, models/ | Enforces validation and domain rules (Invalid email, duplicates). |
| Controllers | controllers/user-controller.ts | userControllerRef | services/, models/ | Translates HTTP/RPC inputs into service calls and status codes. |
| Entrypoint | main.ts | app | controllers/, db/ | Pins shared stateful refs at the root and boots the app. |
Walking the Full MVC Graph
Walk through the six files in the tree below from bottom to top to trace how a request travels through the graph:
db/database.ts:provide(({ onDispose }): Database => { ... })holds the in-memory table map and registers anonDisposehook right next to the state it closes.models/user.ts: Pure TypeScriptinterface User—zero DI imports needed.repositories/user-repository.ts:userRepositoryRefcallsinject(databaseRef)once while its factory runs, grabs the'users'collection, and returns{ findByEmail, create }.services/user-service.ts:userServiceRefinjectsuserRepositoryRefand keeps validation and uniqueness checks out of HTTP handlers.controllers/user-controller.ts:userControllerRefinjectsuserServiceRefand formats the{ status: 201, body }response.main.ts:bootstrapApp()installsproviders: [databaseRef]at the root scope and injectsuserControllerRefinside the startup callback.
- db/
- models/
- repositories/
- services/
- controllers/
1import { provide } from 'dn-ioc'23export interface Database {4 collection<T>(name: string): Map<string, T>5 readonly closed: boolean6}78// Stands in for a stateful SQL or document connection pool9export const databaseRef = provide(({ onDispose }): Database => {10 const tables = new Map<string, Map<string, unknown>>()11 let closed = false1213 onDispose(async () => {14 tables.clear()15 closed = true16 })1718 return {19 collection<T>(name: string) {20 let table = tables.get(name) as Map<string, T> | undefined21 if (!table) {22 table = new Map<string, T>()23 tables.set(name, table)24 }25 return table26 },27 get closed() {28 return closed29 },30 }31})
1export interface User {2 id: string3 email: string4 name: string5}
1import { provide } from 'dn-ioc'2import { databaseRef } from '../db/database'3import type { User } from '../models/user'45export const userRepositoryRef = provide(({ inject }) => {6 const db = inject(databaseRef)7 const users = db.collection<User>('users')89 return {10 async findByEmail(email: string): Promise<User | undefined> {11 return users.get(email)12 },13 async create(user: User): Promise<User> {14 users.set(user.email, user)15 return user16 },17 }18})
1import { provide } from 'dn-ioc'2import type { User } from '../models/user'3import { userRepositoryRef } from '../repositories/user-repository'45export const userServiceRef = provide(({ inject }) => {6 const users = inject(userRepositoryRef)78 return {9 async register(email: string, name: string): Promise<User> {10 if (!email.includes('@')) {11 throw new Error('Invalid email')12 }13 if (await users.findByEmail(email)) {14 throw new Error('Email already taken')15 }16 return users.create({17 id: `usr_${email}`,18 email,19 name,20 })21 },22 }23})
1import { provide } from 'dn-ioc'2import { userServiceRef } from '../services/user-service'34export const userControllerRef = provide(({ inject }) => {5 const userService = inject(userServiceRef)67 return {8 async postRegister(body: { email: string; name: string }) {9 const created = await userService.register(body.email, body.name)10 return { status: 201 as const, body: created }11 },12 }13})
1import { bootstrapApp } from 'dn-ioc'2import { userControllerRef } from './controllers/user-controller'3import { databaseRef } from './db/database'45export const app = bootstrapApp(6 async ({ inject }) => {7 const controller = inject(userControllerRef)8 const response = await controller.postRegister({9 email: 'ada@example.com',10 name: 'Ada Lovelace',11 })12 console.log(response.status, response.body.id) // 201 usr_ada@example.com13 },14 {15 // Install stateful connection refs at the root so every subtree shares one pool16 providers: [databaseRef],17 },18)1920await app.start()21await app.stop()
Why Connection Pools Belong in Root providers
You might wonder: since databaseRef is created with provide(), wouldn't inject(databaseRef) inside userRepositoryRef self-install it automatically even if main.ts omitted providers: [databaseRef]?
In a flat single-scope app, yes—the first inject(databaseRef) at the root scope would cache it there. Listing providers: [databaseRef] explicitly in main.ts protects you as the app grows:
- Remember from Providers & Refs and Scopes & Subtrees that an unregistered
Refself-installs into whichever scope injects it first. - If you later mount two isolated
{ providers }subtrees—say, an admin router and a background job worker—and neither parent registereddatabaseRef, each subtree would quietly spin up its own separate connection pool. - Pinning stateful resources (
databaseRef, Redis clients, rate-limit stores) in rootproviderskeeps instantiation lazy while guaranteeing every subtree in the process shares that single pool and closes it once onawait app.stop().
Workflow: Adding a New Resource Module
Adding a second feature—say, posts—follows a predictable four-step loop without touching existing user modules:
- Add the model (
models/post.ts): Exportinterface Post { id: string; authorId: string; title: string }. - Add the repository (
repositories/post-repository.ts): ExportpostRepositoryRef = provide(({ inject }) => { ... })injecting the existingdatabaseRef. - Add the service (
services/post-service.ts): ExportpostServiceRef = provide(({ inject }) => { ... })injectingpostRepositoryRef(anduserRepositoryRefif it needs to check that the author exists). - Mount the controller (
controllers/post-controller.ts→main.ts): ExportpostControllerRefandinject(postControllerRef)insidemain.tswhen wiring routes.
Notice what you didn't have to touch: there's no central DI manifest to edit for every repository and service, and databaseRef is already shared at the root.
Swapping userRepositoryRef in Unit Tests
Even though userServiceRef imports userRepositoryRef directly, you don't need module-level mocks (vi.mock or mock.module) to test UserService in isolation. Pass provideFor(userRepositoryRef, fakeUserRepository) to bootstrapApp() in your test:
userServiceRefreceives your in-memoryMapfake instead of the real repository.- Because
userRepositoryRef's default factory never runs,databaseRefis never even instantiated during the test.
1import { bootstrapApp, provideFor } from 'dn-ioc'2import type { User } from './models/user'3import { userRepositoryRef } from './repositories/user-repository'4import { userServiceRef } from './services/user-service'56const stored = new Map<string, User>()78const fakeUserRepository = () => ({9 findByEmail: async (email: string) => stored.get(email),10 create: async (user: User) => {11 stored.set(user.email, user)12 return user13 },14})1516export const testApp = bootstrapApp(17 async ({ inject }) => {18 const service = inject(userServiceRef)19 const created = await service.register('grace@example.com', 'Grace Hopper')20 console.log(created.email, stored.size) // grace@example.com 121 },22 {23 providers: [provideFor(userRepositoryRef, fakeUserRepository)],24 },25)2627await testApp.start()28await testApp.stop()