dn-ioc

07 · Core Kernel

Async Providers

Opening a database pool, fetching remote secrets, or warming an in-memory cache shouldn't force you onto a separate provideAsync() / injectAsync() API track. In dn-ioc, you just write an async factory: inject() returns a standard Promise<T> and shares that single in-flight Promise across every caller in the same scope.

shared-promise.ts
1export const settingsRef = provide(async () => ({ status: 'ready' as const }))23export const sharedApp = bootstrapApp(async ({ inject }) => {4  const first = inject(settingsRef)5  const second = inject(settingsRef)6  console.log(first === second) // true7  console.log((await first).status) // ready8})910await sharedApp.start()11await sharedApp.stop()

Shared Promise Identity & Retry on Failure

inject() never wraps synchronous values in Promises—sync factories return T directly, and async factories return Promise<T>.

When sharedApp calls inject(settingsRef) twice back-to-back in the same resolution scope, the factory runs only once and both callers receive the exact same Promise instance (first === second is true). You don't have to write manual memoization guards to stop five services from opening five duplicate database handshakes at boot.

What if an async provider rejects—say, a transient network hiccup times out?

  • Automatic cache eviction on rejection: As soon as the factory's Promise rejects, the kernel removes that failed pending entry from the scope's cache before propagating the error.
  • Clean retries while running: As long as the app hasn't been stopped, a later inject() call in that scope will run the factory fresh instead of replaying a permanently poisoned rejection.

Awaited Startup vs Background Work

app.start() follows a simple rule: it waits only for your root factory and whatever Promises your root factory actually awaits or returns. That gives you crisp control over what blocks startup and what doesn't:

  • Block start() on critical dependencies: await inject(settingsRef) inside bootstrapApp(async ({ inject }) => { ... }) when the app shouldn't report ready until that resource settles. If it rejects, start() automatically runs cleanup and rejects.
  • Kick off non-blocking background work: Trigger inject(warmupRef) without awaiting it inside the root factory, and app.start() resolves right away while warmupRef keeps running. Always assign that unawaited Promise to an owner outside the root factory (like warmupTask in background-task.ts) so you can still observe its result or catch errors—detached Promises aren't tracked by start().
background-task.ts
1export const warmupRef = provide(async () => 'cache-warmed')23export let warmupTask!: Promise<string>45export const backgroundApp = bootstrapApp(({ inject }) => {6  // Started without await: start() does not wait for warmupTask to settle7  warmupTask = inject(warmupRef)8})910await backgroundApp.start()11console.log(await warmupTask) // cache-warmed12await backgroundApp.stop()

Typing Async Tokens

With provide(async () => ...), TypeScript sees the async function return type and infers Ref<Promise<T>> automatically. A token(), on the other hand, has no factory function to infer from—so for an async token, put Promise<...> directly inside the type parameter.

Writing token<Promise<Settings>>('Settings') makes the contract unambiguous on both ends: consumers see right away that inject(settingsToken) returns a Promise they need to await, and provideFor(settingsToken, ...) type-checks that the bound adapter returns Promise<Settings>.

async-token.ts
1export interface Settings {2  ready: boolean3}45export const settingsToken = token<Promise<Settings>>('Settings')67export const asyncTokenApp = bootstrapApp(8  async ({ inject }) => {9    const settings = await inject(settingsToken)10    console.log(settings.ready) // true11  },12  {13    providers: [provideFor(settingsToken, async () => ({ ready: true }))],14  },15)1617await asyncTokenApp.start()18await asyncTokenApp.stop()

Async Cycles & Shutdown Boundaries

  • Deadlock-free cycle detection: The kernel tracks in-flight async dependency edges across await boundaries. If pending provider A awaits B while B circles back to await A, inject() throws Circular dependency detected: A -> B -> A immediately instead of hanging your process forever.