For AI agents: the complete documentation index is available at https://navios.tech/llms.txt, the full documentation bundle is available at https://navios.tech/llms-full.txt, and this page is available as Markdown at https://navios.tech/docs/di/reference/api.md.

API

Everything exported by @navios/di and @navios/di/testing. Each entry links to the page that explains it; this page only lists signatures.

Containers

Container

new Container(options?: ContainerOptions)
OptionTypeDefaultPurpose
providersProvider[][]Bindings created with provide()
strictbooleanfalseIgnore default providers. See Strict containers
loggerConsole | null—Receives an error when a destroy hook or an onInvalidate listener throws with nobody to receive it, and a warning when invalidate() is given an unknown instance. Without one, errors go to console.error(); null drops them
MemberReturnsDescription
get(token, args?)Promise<T>Resolves an instance, waiting for anything asynchronous
getSync(token, args?)TResolves synchronously. Throws AsyncInitRequired if something has to be awaited
peek(token, args?)T | nullReturns an instance that already exists. Never builds
provide(target, impl)voidAdds a provider. Throws once the token is resolved
decorate(target, fn)voidWraps every instance built for a token. Throws once the token is resolved. Not applied to { value } providers or addInstance() values
addInstance(target, value)voidStores a ready value as a singleton
isRegistered(target)booleanWhether the token has an instance or a provider here
getProvider(target)ProviderInfo | undefinedThe provider that would be used
instances()unknown[]Every instance currently held, dependencies before their dependents, each object once, without the container itself
createScope(metadata?)ScopedContainerCreates a scope
invalidate(instance)Promise<void>Destroys an instance and its dependents
onInvalidate(token, args, listener)() => voidListens for the destruction of an instance. Returns an unsubscribe function
ready()Promise<void>Resolves when nothing is still being created
dispose()Promise<void>Destroys everything the container holds and closes it
[Symbol.asyncDispose]()Promise<void>Calls dispose()

Container is itself injectable: inject(Container) returns the root container.

ScopedContainer

Created by container.createScope(). It has get, getSync, peek, addInstance, isRegistered, invalidate, onInvalidate, ready, dispose and [Symbol.asyncDispose] with the signatures above, and adds:

MemberReturnsDescription
parentContainerThe root container
getMetadata(key)anyReads the metadata given to createScope()
setMetadata(key, value)voidChanges it

addInstance() on a scope stores a request-scoped value. A scope has no provide(), decorate() or getProvider(); those belong to the root.

inject(ScopedContainer) returns the current scope in a request-scoped service.

IContainer

The interface both containers implement: get, getSync, peek, invalidate, onInvalidate, isRegistered, addInstance, dispose, ready. It is the type of FactoryContext.container.

Registration

ExportSignatureDescribed in
Injectable(options?: { scope?, token?, schema? }) => ClassDecoratorServices and injection
Factory(options?: { scope?, token? }) => ClassDecoratorFactories
registerInjectable(target, options?: RegisterInjectableOptions) => InjectionTokenServices and injection
registerFactory(target, options?: RegisterFactoryOptions) => InjectionTokenFactories
registerProvider(target, impl: ProviderInput<T>, options?: RegisterProviderOptions) => InjectionTokenProviders
provide(target: ClassType | InjectionToken<T>, impl: ProviderInput<T>) => ProviderProviders
getInjectableToken(target: ClassType) => InjectionToken. Throws ClassNotInjectable when unregisteredTokens

Only a registration on the class itself counts. An undecorated subclass of an injectable class has no token.

Option types: InjectableOptions, FactoryOptions, RegisterInjectableOptions, RegisterFactoryOptions, RegisterProviderOptions, ContainerOptions. ClassType is any class, ClassTypeWithInstance<T> one whose instances are a T, and ResolvedInstance<C> what a class resolves to: its instance, or the product of a factory class.

// Only the public members of `T` count.
type ProviderInput<T> =
  | ClassTypeWithInstance<T | Factorable<T>>
  | { value: T }
  | { class: ClassTypeWithInstance<T | Factorable<T>>; scope?: InjectableScope }
  | { factory: (ctx: FactoryContext, args: any) => T | Promise<T>; scope?: InjectableScope }
  | { existing: ClassTypeWithInstance<T> | InjectionToken<T> } // or a bound or factory token

// The result of `provide()`; pass it on as it is.
interface Provider {
  readonly token: InjectionToken<any, any>
}

interface ProviderInfo {
  readonly kind: 'class' | 'factory' | 'function' | 'value' | 'existing'
  readonly scope: InjectableScope
  readonly target: ClassType | undefined
}

Injection functions

All three can only be called while a class or factory is being built, before its first await. See Services and injection.

ExportReturnsDescription
injectTThe instance, built on the spot if needed
optionalT | nullThe instance, or null when nothing provides the token
asyncInjectPromise<T>Starts resolving after the current constructor returns. For breaking cycles

Each takes (token, args?). Their overloads are exported as the types SyncResolve, OptionalResolve and AsyncResolve; container.getSync, container.peek and container.get share them, and so does ctx.inject the last. When a token requires arguments and none are given, the return type is the string type MissingArgsError<S>, which names the missing keys.

Tokens

See Tokens.

class InjectionToken<T, S = unknown> {
  readonly name: string | symbol | ClassType
  readonly schema: StandardSchemaV1 | undefined
  readonly scope: InjectableScope | undefined

  static create<T>(name: string | symbol): InjectionToken<T, undefined>
  static create<C>(name: C): InjectionToken<InstanceType<C>, undefined> // C: a class
  static create<T, S extends StandardSchemaV1>(name: string | symbol, schema: S): InjectionToken<T, S>
  static create<T>(name: string | symbol, options: { scope?: InjectableScope }): InjectionToken<T, undefined>
  static create<T, S extends StandardSchemaV1>(
    name: string | symbol,
    options: { scope?: InjectableScope; schema: S },
  ): InjectionToken<T, S>

  static bound<T, S extends StandardSchemaV1>(
    token: InjectionToken<T, S>,
    value: InferInput<S>,
  ): BoundInjectionToken<T, S>

  static factory<T, S extends StandardSchemaV1>(
    token: InjectionToken<T, S>,
    factory: (ctx: FactoryContext) => InferInput<S> | Promise<InferInput<S>>,
  ): FactoryInjectionToken<T, S>

  static refineType<T>(token: BoundInjectionToken<any, any>): BoundInjectionToken<T, any>

  toString(): string // the name
}
ExportDescription
BoundInjectionTokenResult of InjectionToken.bound(). Fields: token, value, name, schema
FactoryInjectionTokenResult of InjectionToken.factory(). Fields: token, factory, name, schema
InjectionTokenOptions{ schema?, scope? }
AnyInjectableTypeA class or any of the three token classes: whatever get() and inject() accept
InjectionTokenTypeAny of the three token classes

Factories and lifecycle

ExportShapeDescribed in
FactoryContext{ inject: AsyncResolve; container: IContainer; addDestroyListener(listener): void }Factories
Factorable<T>{ create(ctx?: FactoryContext): T | Promise<T> }Factories
FactorableWithArgs<T, S>{ create(ctx: FactoryContext | undefined, args: InferOutput<S>): T | Promise<T> }Factories
OnServiceInit{ onServiceInit(): void | Promise<void> }Lifecycle
OnServiceDestroy{ onServiceDestroy(): void | Promise<void> }Lifecycle

InjectableScope

enum InjectableScope {
  Singleton = 'Singleton',
  Transient = 'Transient',
  Request = 'Request',
}

See Scopes.

Schema types

@navios/di contains its own copy of the Standard Schema types, so it depends on no schema library.

ExportDescription
StandardSchemaV1<Input, Output>The Standard Schema interface
StandardSchemaIssueWhat a schema reports
InferInput<S>, InferOutput<S>The input and output type of a schema

Error codes

Every failure raised by the container is a DIError. What a decorator, an onInvalidate listener or other code of yours throws outside a construction is passed on as it is.

An error never carries the arguments of a token, which may hold secrets and would end up in logs.

class DIError extends Error {
  readonly code: DIErrorCode
  readonly context?: Record<string, unknown>
  readonly cause?: unknown
}
DIErrorCodeRaised whencontext
ProviderNotFoundNo instance and no provider exists for the tokenname, path
ClassNotInjectableA class without @Injectable or @Factory is resolved, provided or storedclassName
ScopeMismatchErrorA request-scoped service is reached from the root container or from a singleton, or its value is added to the rootname, path
CircularDependencyServices depend on each other in a cyclecycle
ProviderConflictA second default provider is registered for a tokentoken, existing, incoming
TokenValidationErrorArguments fail the token's schema, or the schema throws or validates asynchronouslyname, issues ({ path, message }[])
TokenSchemaRequiredErroraddInstance() is called with a token whose arguments are requiredname
AsyncInitRequiredgetSync() meets something that has to be awaited, or that is being destroyedname
InitializationErrorA constructor, factory or onServiceInit throws something that is not a DIErrorserviceName, error; cause is set
ContainerDisposedA disposed container or scope is used, or disposed while a resolution is in flightkind
OutsideInjectionContextinject(), optional() or asyncInject() is called outside a constructionwhat
AccessBeforeInitA constructor uses a placeholdername
UnknownErrorMisuse without a code of its own: provide() after resolution, a second addInstance(), a value that is not a class or token, a decorator on something it does not apply to, a token of another copy of the package—

The messages, for matching against logs. In code, compare code.

DIErrorCodeMessage
ProviderNotFoundNo provider for <name> (<path>)
ClassNotInjectableClass <name> is not decorated with @Injectable.
ScopeMismatchErrorScope mismatch: <name> is request-scoped and cannot be resolved from the root container (<path>). …
CircularDependencyCircular dependency detected: A -> B -> A
ProviderConflictToken <token> already has a default provider (<existing>); <incoming> cannot become a second default. …
TokenValidationErrorInvalid args for <token>: <path>: <message>; …, or : token args schemas must validate synchronously
TokenSchemaRequiredErrorToken <token> requires args, so addInstance() needs to know which: …
AsyncInitRequired<name> or one of its dependencies has an asynchronous initializer and cannot be resolved synchronously. …
InitializationErrorService <name> initialization failed: <original message>
ContainerDisposedContainer has been disposed or ScopedContainer has been disposed
OutsideInjectionContext<function>() can only be called synchronously while a class or factory is being built; …
AccessBeforeInit[Injector] Trying to access <name> before it's initialized, please move the code to a onServiceInit method

AccessBeforeInit is thrown inside a construction pass that the container discards and repeats, so it is seen only by code that catches it in the constructor or keeps the placeholder and uses it later.

import { DIError, DIErrorCode } from '@navios/di'

try {
  await container.get(UserService)
} catch (error) {
  if (error instanceof DIError && error.code === DIErrorCode.InitializationError) {
    console.error(error.cause)
  }
}

Testing

Exported from @navios/di/testing. See Testing.

TestContainer

new TestContainer(options?: { logger?: Console | null })

Extends Container.

MemberDescription
bind(target)Returns a BindingBuilder with toValue(value), toClass(cls) and toFactory(fn)
clear()Destroys all instances and resets recorded calls and events. Bindings stay, and the container stays usable
expectResolved(target), expectNotResolved(target)Whether the container holds an instance for the token
expectSingleton(target), expectTransient(target), expectRequestScoped(target)The scope of the provider in use
expectSameInstance(target), expectDifferentInstances(target)Resolves twice and compares. Both return a promise
recordMethodCall(target, method, args, result?, error?)Reports a call, for use inside a fake
expectCalled(target, method), expectCalledWith(target, method, args), expectCallCount(target, method, count)Assert on reported calls
getMethodCalls(target), clearMethodCalls()Read and reset reported calls
recordLifecycleEvent(target, event, instanceName)Reports 'created', 'initialized' or 'destroyed'
expectInitialized(target), expectDestroyed(target), expectNotDestroyed(target)Assert on reported lifecycle events
getServiceStats(target){ instanceCount, methodCalls, lifecycleEvents }
getDependencyGraph(){ nodes, rootTokens } for the resolved instances, with scope, dependencies and dependents
getSimplifiedDependencyGraph()Record<string, string[]>: token name to sorted dependency names

UnitTestContainer

new UnitTestContainer(options: {
  providers: ProviderConfig[]
  allowUnregistered?: boolean
  logger?: Console | null
})

interface ProviderConfig<T = any> {
  token: ClassType | InjectionToken<T, any> | BoundInjectionToken<T, any>
  useValue?: T // the public members of T, as for provide()
  useClass?: new (...args: any[]) => T
  useFactory?: (ctx: FactoryContext, args: any) => T | Promise<T>
}

Extends Container in strict mode. Objects returned by get() and getSync(), of the container and of its scopes, record their method calls.

MemberDescription
clear()Destroys all instances and resets recorded calls and events. Providers stay, and the container stays usable
enableAutoMocking(), disableAutoMocking()Switch allowUnregistered on or off. Both return the container
expectResolved(target), expectNotResolved(target)Whether the container holds an instance for the token
expectAutoMocked(target), expectNotAutoMocked(target)Whether a placeholder was handed out for the token
expectCalled(target, method), expectNotCalled(target, method), expectCalledWith(target, method, args), expectCallCount(target, method, count)Assert on recorded calls
getMethodCalls(target), clearMethodCalls()Read and reset recorded calls
recordLifecycleEvent(target, event, instanceName)Reports a lifecycle event
expectInitialized(target), expectDestroyed(target), expectNotDestroyed(target)Assert on reported lifecycle events
getServiceStats(target){ instanceCount, methodCalls, lifecycleEvents }
getRegisteredTokens(), getAutoMockedTokens()ReadonlySet<InjectionToken> of listed and auto-mocked tokens

Testing types

BindingBuilder<T>, ProviderConfig<T>, TestContainerOptions, UnitTestContainerOptions, MethodCallRecord ({ method, args, timestamp, result?, error? }), LifecycleRecord ({ event, timestamp, instanceName }), MockServiceStats, DependencyNode, DependencyGraph.