dn-ioc

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.

mvc-project
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:

LayerFileExportsAllowed project importsResponsibility
Modelsmodels/user.tstype UserNoneShared TypeScript interfaces and value shapes.
Databasedb/database.tsdatabaseRefNoneOwns the connection pool and registers onDispose() cleanup.
Repositoriesrepositories/user-repository.tsuserRepositoryRefdb/, models/Encapsulates collection/SQL queries behind typed methods.
Servicesservices/user-service.tsuserServiceRefrepositories/, models/Enforces validation and domain rules (Invalid email, duplicates).
Controllerscontrollers/user-controller.tsuserControllerRefservices/, models/Translates HTTP/RPC inputs into service calls and status codes.
Entrypointmain.tsappcontrollers/, 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:

  1. db/database.ts: provide(({ onDispose }): Database => { ... }) holds the in-memory table map and registers an onDispose hook right next to the state it closes.
  2. models/user.ts: Pure TypeScript interface User—zero DI imports needed.
  3. repositories/user-repository.ts: userRepositoryRef calls inject(databaseRef) once while its factory runs, grabs the 'users' collection, and returns { findByEmail, create }.
  4. services/user-service.ts: userServiceRef injects userRepositoryRef and keeps validation and uniqueness checks out of HTTP handlers.
  5. controllers/user-controller.ts: userControllerRef injects userServiceRef and formats the { status: 201, body } response.
  6. main.ts: bootstrapApp() installs providers: [databaseRef] at the root scope and injects userControllerRef inside the startup callback.
db/database.ts
  • 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 Ref self-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 registered databaseRef, each subtree would quietly spin up its own separate connection pool.
  • Pinning stateful resources (databaseRef, Redis clients, rate-limit stores) in root providers keeps instantiation lazy while guaranteeing every subtree in the process shares that single pool and closes it once on await 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:

  1. Add the model (models/post.ts): Export interface Post { id: string; authorId: string; title: string }.
  2. Add the repository (repositories/post-repository.ts): Export postRepositoryRef = provide(({ inject }) => { ... }) injecting the existing databaseRef.
  3. Add the service (services/post-service.ts): Export postServiceRef = provide(({ inject }) => { ... }) injecting postRepositoryRef (and userRepositoryRef if it needs to check that the author exists).
  4. Mount the controller (controllers/post-controller.ts → main.ts): Export postControllerRef and inject(postControllerRef) inside main.ts when 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:

  • userServiceRef receives your in-memory Map fake instead of the real repository.
  • Because userRepositoryRef's default factory never runs, databaseRef is never even instantiated during the test.
services/user-service.test.ts
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()