API

Import public macros from compdi/macros. For usage guidance, start with the lifecycle comparison; use this page when you already know which macro you need.

Lifecycle

defineAppTeardown(resources)

Defines an async teardown function that disposes the supplied resources in reverse order. Supported disposal protocols are resolved at build time.

This macro is experimental and may be removed in a future release.

Example:

const teardown = defineAppTeardown([server, database]);
await teardown();

Scoped

createScoped(options)

Creates a stable object proxy that resolves one value per active context and returns it with a non-creating lifecycle controller.

Example:

const [database, scope] = createScoped({
  factory: request => createDatabase(request),
  context: useRequest,
});
scope.release(request);

defineScoped(options)

Defines a keyed per-context accessor with has, peek, and release lifecycle methods.

Example:

const useService = defineScoped<Service, Request>({
  target: Service,
  deps: [database],
});
const service = useService(request);

Singleton

createSingleton(options)

Creates one eagerly initialized application-wide value from a class target or factory. Async factories return a promise.

Example:

const database = createSingleton({ target: Database, deps: [config] });

defineSingleton(options)

Defines an accessor for one application-wide value. Pass lazy: true to defer construction until the first accessor call.

Example:

const useDatabase = defineSingleton({ target: Database, lazy: true });
const database = useDatabase();

Transient

createTransient(options)

Defines a factory that constructs a fresh value on every call.

Example:

const createService = createTransient({ target: Service, deps: [database] });
const service = createService();

defineTransient(options)

Defines a factory that constructs a fresh value on every call.

Example:

const createService = defineTransient({ target: Service, deps: [database] });
const service = createService();