09 · Engineering Patterns
Choosing Ref vs Token
When you start structuring a real codebase with dn-ioc, the first design question you'll hit is whether a dependency should be a Ref<T> from provide() or a Token<T> from token(). You don't have to guess or treat it as a matter of style—module import direction settles the choice every single time.
- mvc/
- services/
- repositories/
- services/
- ddd/
- application/
- domain/
- application/
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 { 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 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})
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')
Import Direction Is the Decision Rule
Ask one question about the module calling inject(): is this file allowed to import the concrete implementation?
- Yes → use
provide()(Ref<T>): ARefbundles its key and its factory function into one export. ImportinguserRepositoryRefinuser-service.tspullsuser-repository.ts—and whateverdatabaseRefit imports—straight into your module graph. In a layered MVC service where controllers import services and services import repositories, that's exactly what you want: zero extra files, zero central registration boilerplate, and full type inference. - No → use
token<T>()(Token<T>): ATokencarries only a TypeScript type and an optional diagnostic string—zero runtime code. In DDD / Clean Architecture, your innerdomain/layer definesOrderRepositoryand exportsorderRepositoryToken, while your outerinfra/layer importsdomain/and binds the SQL implementation withprovideFor(). Your core business logic never imports a database driver, an HTTP SDK, orinfra/.
Tokens also shine whenever a value only exists at startup—like environment URLs, API credentials, or per-subtree configuration—where there's no sensible default factory to write in the first place.
Side-by-Side Trade-Offs
Browse the four files in the tree above (mvc/ vs ddd/) against the practical trade-offs below:
| Dimension | Ref<T> (provide()) | Token<T> (token() + provideFor()) |
|---|---|---|
| Compile-time coupling | Consumer imports the concrete module directly. | Consumer imports only the contract; outer layer imports the contract to bind it. |
| Wiring boilerplate | Zero—self-installs on first inject() in the active scope. | Explicit—must be bound via provideFor() in { providers } or a bundle. |
| Swapping in tests | provideFor(ref, fakeFactory) | provideFor(token, fakeFactory) — exact same helper. |
| Forgotten fake in a unit test | Silent fallback: builds and runs the real implementation. | Fast failure: rejects start() with No provider for token: Name. |
| Diagnostic name in errors | Function name (const UserService = ...; provide(UserService)), or <anonymous>. | Description string (token('OrderRepository')), or <anonymous>. |
| Best fit | MVC controllers, services, repositories, use cases, internal helpers. | DDD domain ports, cross-cutting ports (Clock, Mailer), runtime config/secrets. |
Mixing Both in the Same Codebase
Choosing between Ref and Token isn't a repo-wide religion—most production apps use both right next to each other:
- Even in a strict DDD service, application use cases (
orderServiceRef) and private infrastructure clients (sqlTableRef) are plainRefs because their callers live in outer or same-tier modules that are meant to import them. Only the boundary ports crossing from inner layers to outer adapters needtoken(). - Even in a straightforward MVC app, you can reach for
token()for a runtimeDatabaseUrlstring or a third-party payment gateway you never want unit tests hitting by accident.
Next, let's walk through both patterns across complete, multi-file projects: start with MVC Pattern in Practice for direct top-down composition, or flip to DDD & Clean Architecture for port-and-adapter inversion.