dn-ioc

05 · Core Kernel

Tokens & Binding

Reach for token<T>() when the code asking for a dependency shouldn't import—or doesn't yet know—the concrete implementation behind it. Runtime secrets like database URLs, pluggable UI themes, and pure DDD domain ports all fit here: you define a typed placeholder up front and wire the real value later with provideFor().

bound-token.ts
1export const prefixToken = token<string>('Prefix')23export const formatterRef = provide(({ inject }) => {4  const prefix = inject(prefixToken)5  return {6    format: (value: string) => `${prefix}${value}`,7  }8})910export const boundApp = bootstrapApp(11  ({ inject }) => {12    console.log(inject(formatterRef).format('ready')) // [app] ready13  },14  {15    providers: [provideFor(prefixToken, () => '[app] '), formatterRef],16  },17)1819await boundApp.start()

Declaring Contracts with token() and provideFor()

Where provide() bundles a key and its default factory together, token<T>(description?) creates only the key. It holds zero runtime logic and pulls in zero implementation imports—TypeScript carries the type T, and the optional description string gives humans a clear label in error messages.

To supply an implementation, pass the token and a factory to provideFor(key, factory, options?):

  • In bound-token.ts, prefixToken declares that someone must supply a string.
  • formatterRef injects prefixToken without knowing whether that prefix comes from an environment variable, a config file, or a test stub.
  • boundApp installs provideFor(prefixToken, () => '[app] ') at bootstrap, so formatterRef prints [app] ready.

Notice that provideFor() accepts any InjectKey<T>—meaning both a Token<T> and a Ref<T>. You use the exact same helper to bind an abstract port in production or swap out a concrete Ref in a test.

Failing Fast When a Token Is Unbound

Because a Token<T> has no fallback factory, injecting one that hasn't been bound in the active scope or any parent scope throws immediately. In unbound-token.ts, unboundApp.start() rejects with No provider for token: DatabaseUrl—matching No provider for token: Name, where Name is the description passed to token().

unbound-token.ts
1export const databaseUrlToken = token<string>('DatabaseUrl')23export const unboundApp = bootstrapApp(({ inject }) => {4  inject(databaseUrlToken)5})67try {8  await unboundApp.start()9} catch (error) {10  console.error((error as Error).message) // No provider for token: DatabaseUrl11}

Naming Tokens & Factories for Clear Diagnostics

Readable error messages save real debugging time when a token goes unbound or two providers accidentally form a loop (Circular dependency detected: A -> B -> A). Here's where those names come from:

  • Tokens use their description string: Name a token after the type or setting it represents—for example, token<OrderRepository>('OrderRepository') or token<string>('DatabaseUrl'). If you omit the description (token<string>()), errors report <anonymous>.
  • Refs use factory.name: provide() doesn't take a separate label argument—it reads the JavaScript function's .name property. Assigning an arrow factory to a named const (const Formatter = ({ inject }: Context) => { ... }; provide(Formatter)) gives the ref the diagnostic name Formatter, whereas an inline arrow (provide(({ inject }) => ...)) has no name of its own and reports <anonymous>.