On this page

@zirion/ioc · API reference

API reference

Public API of @zirion/ioc v3: Container, provider options, async and sync resolution, scopes, lifecycle contracts, and exported types.

Updated · ·

new Container(options?)

Starts an empty container.

const container = new Container({ logger });

options.logger can be an ILogger object, class, or zero-argument factory. Without it, the container uses ConsoleLoggerImpl.

container.add(selector, options?)

Registers one provider and returns the container, with the selector added to its TypeScript type.

container.add(Service, {
  inject: [DependencyA, DependencyB],
  scope: InjectScope.TRANSIENT,
  valueFactory: async ([a, b], context) => new Service(a, b),
});
Option Default Description
inject undefined Selectors to resolve before creating this value, in argument order
scope InjectScope.TRANSIENT Fresh, shared by the container, or tied to a context
valueFactory undefined A function that creates the value; it may be async

A class selector can be created without a factory. Other selectors need valueFactory.

container.get(selector, context?)

Returns a promise for the value or null when the selector is unknown. Other resolution errors still reject the promise.

container.getOrFail(selector, context?)

Returns a promise for the value. An unknown selector throws DependencyInjectionError with code UNKNOWN_TARGET.

container.getSync(selector, context?)

Returns the value synchronously, or null for a missing runtime registration. Throws ASYNC_RESOLUTION_REQUIRED if resolution requires a promise.

container.getOrFailSync(selector, context?)

Returns a value synchronously. A missing runtime registration throws UNKNOWN_TARGET; async work throws ASYNC_RESOLUTION_REQUIRED.

container.finalize() / container.build()

Runs and awaits onFinalized() on object selectors and singleton class instances, then returns the container. build() calls finalize(). Request and transient classes are skipped; resources are not disposed.

container.logger

The logger set when the container was created.

InjectScope

enum InjectScope {
  SINGLETON = 'singleton',
  REQUEST = 'request',
  TRANSIENT = 'transient',
}

Lifecycle contracts

interface IOnInitialized {
  onInitialized(): void | Promise<void>;
}

interface IOnFinalized {
  onFinalized(): void | Promise<void>;
}

Other exported types

The package also exports Type, MaybePromise, TSelector, TValueFactory, TTargetOptions, TStorageEntry, TContainerOptions, ILogFunction, TRegistration, TRegisteredValue, TFactoryResult, TResolutionCache, and ILogger. Most application code needs only TTargetOptions or ILogger; storage types are mainly for library internals.

Back to top