dn-ioc

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/user-service.ts
  • mvc/
    • services/
    • repositories/
  • ddd/
    • application/
    • domain/
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>): A Ref bundles its key and its factory function into one export. Importing userRepositoryRef in user-service.ts pulls user-repository.ts—and whatever databaseRef it 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>): A Token carries only a TypeScript type and an optional diagnostic string—zero runtime code. In DDD / Clean Architecture, your inner domain/ layer defines OrderRepository and exports orderRepositoryToken, while your outer infra/ layer imports domain/ and binds the SQL implementation with provideFor(). Your core business logic never imports a database driver, an HTTP SDK, or infra/.

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:

DimensionRef<T> (provide())Token<T> (token() + provideFor())
Compile-time couplingConsumer imports the concrete module directly.Consumer imports only the contract; outer layer imports the contract to bind it.
Wiring boilerplateZero—self-installs on first inject() in the active scope.Explicit—must be bound via provideFor() in { providers } or a bundle.
Swapping in testsprovideFor(ref, fakeFactory)provideFor(token, fakeFactory) — exact same helper.
Forgotten fake in a unit testSilent fallback: builds and runs the real implementation.Fast failure: rejects start() with No provider for token: Name.
Diagnostic name in errorsFunction name (const UserService = ...; provide(UserService)), or <anonymous>.Description string (token('OrderRepository')), or <anonymous>.
Best fitMVC 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 plain Refs 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 need token().
  • Even in a straightforward MVC app, you can reach for token() for a runtime DatabaseUrl string 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.