Open MercatoDocsSearch docsAPI reference

Framework

Dependency injection container

A route needs the entity manager and services for its own request. A worker needs an equivalent scope when it handles a job later. Register the shared service contract once and resolve it from the container for the operation being performed.

Open Mercato uses Awilix to assemble services at runtime. Each HTTP request, background job, or CLI command spins up a scoped container with core services and module contributions.

Container creation

import { asClass } from 'awilix';
import type { AppContainer } from '@/lib/di/container';
import { AuthService } from './services/auth-service';

export function register(container: AppContainer) {
  container.register({
    authService: asClass(AuthService).scoped(),
  });
}

Resolving services

App-level overrides

Standalone and monorepo apps can register application-specific services in src/di.ts:

import { asValue } from 'awilix'
import type { AppContainer } from '@open-mercato/shared/lib/di/container'

export function register(container: AppContainer) {
  container.register({ applicationPolicy: asValue({ enabled: true }) })
}

The scaffolded src/bootstrap.ts passes this function explicitly to the shared bootstrap factory:

import { register as registerAppDi } from '@/di'

export const bootstrap = createBootstrap(data, {
  appDiRegistrar: registerAppDi,
})

Explicit wiring keeps the app alias in the app's bundler context, so scaffolded apps do not rely on package code resolving @/di on their behalf. A package-level dynamic-import fallback remains only for compatibility with older app bootstraps. The registrar runs for each request container after core and module registrars; inline modules.ts DI overrides remain the final mutation tier.

Worker, scheduler and CLI processes never load src/bootstrap.ts – they bootstrap through bootstrapFromAppRoot(), which compiles src/di.ts from the app root and wires the same appDiRegistrar. So one register() covers every process. An app without src/di.ts is the supported case; a src/di.ts that fails to compile or exports no register is logged at error level and skipped rather than taking the process down.

Best practices

The DI container is the backbone of module composability – treat it as the single source of truth for service wiring.

Previous: How feature toggles work · Next: Building on the Communications Hub