Class ContainerInstance

The Container.

A container allows you to get, set, and modify dependencies in-place. You can also attach individual services to a container, using them to store services for later execution.

See

https://typedi.js.org/docs/guide/containers/introduction

Example

const container = defaultContainer.ofChild('my-new-container');

@Service({ container })
class MyService { }

Hierarchy

  • ContainerInstance

Implements

  • Disposable

Constructors

Properties

disposed: boolean = false

Indicates if the container has been disposed or not. Any function call should fail when called after being disposed.

Remarks

This is readonly for outside consumers. Its value will change to true if the instance is disposed.

The ID of this container. This will always be unique.

isRetrievingPrivateToken: boolean = false

Whether the container is currently retrieving an identifier which visitors should not be notified of.

This is used to prevent ContainerInstance.getManyOrNull from notifying visitors that it is retrieving a masked token, which is used to store services of { multiple: true }.

metadataMap: Map<ServiceIdentifier, ServiceMetadata<unknown>> = ...

Metadata for all registered services in this container.

multiServiceIds: Map<ServiceIdentifier, ManyServicesMetadata> = ...

Services registered with 'multiple: true' are saved as simple services with a generated token and the mapping between the original ID and the generated one is stored here. This is handled like this to allow simplifying the inner workings of the service instance.

The parent of the container to create. The parent is used for resolving identifiers which are not present in this container.

visitor: VisitorCollection = ...

The currently-present visitors attached to the container. These are conjoined into a container of individual visitors, which implements the standard ContainerTreeVisitor interface, and individual listeners can be added and removed at will.

See

defaultContainer: ContainerInstance = ...

The default global container. By default services are registered into this container when registered via Container.set() or @Service decorator.

Methods

  • Dispose the container, rendering it unable to perform any further injection or storage.

    Returns Promise<void>

    A promise that resolves when the disposal process is complete.

    Async

    Remarks

    It is currently not advised to dispose of the default container. This would result in resolution issues in your application.

    Example

    const appContainer = Container.of('app');

    appContainer.dispose().then(
    () => console.log('The container has been disposed.')
    );

    appContainer.disposed === true;

    // This will throw an error:
    appContainer.get(
    new Token<unknown>('test')
    );

    Throws

    Error This exception is thrown if the container has been disposed.

  • Check if the given service is able to be destroyed and, if so, destroys it in-place.

    Parameters

    • serviceMetadata: ServiceMetadata<unknown>

      the service metadata containing the instance to destroy

    • force: boolean = false

      when true the service will be always destroyed even if it's cannot be re-created

    Returns void

    Deprecated

    Remarks

    If the service contains a method named destroy, it is called. However, the value it returns is ignored.

  • Get the value for the identifier in the current container. If the identifier cannot be resolved locally, the parent tree (if present) is recursively searched until a match is found (or the tree is exhausted).

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to get the value of.

    • Optional recursive: boolean

    Returns T

    The value of the identifier in the current scope.

    Throws

    ServiceNotFoundError This exception is thrown if the identifier cannot be found in the tree.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Return the location of the given identifier. If recursive mode is enabled, the symbol is not available locally, and we have a parent, we tell the parent to search its tree recursively too. If the container tree is substantial, this operation may affect performance.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier of the service to look up.

    • recursive: boolean = true

    Returns ServiceIdentifierLocation

    A ServiceIdentifierLocation.

    • If the identifier cannot be found, ServiceIdentifierLocation.None | None.
    • If the identifier is found locally, ServiceIdentifierLocation.Local | Local.
    • If the identifier is found upstream, ServiceIdentifierLocation.Parent | Parent.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Gets all instances registered in the container of the given service identifier. Used when service are defined with the { multiple: true } option.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to resolve.

    • Optional recursive: boolean

    Returns T[]

    An array containing the service instances for the given identifier.

    Example

    Container.set({ id: 'key', value: 1, multiple: true });
    Container.set({ id: 'key', value: 2, multiple: true });
    Container.set({ id: 'key', value: 3, multiple: true });

    const [one, two, three] = Container.getMany('key');

    Throws

    ServiceNotFoundError This exception is thrown if a value could not be found for the given identifier.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Gets all instances registered in the container of the given service identifier, or the default value if no instances could be found. Used when service are defined with the { multiple: true } option.

    Type Parameters

    • U

      The type of the provided default value.

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to resolve.

    • defaultValue: U
    • recursive: boolean = true

    Returns U | T[]

    An array containing the service instances for the given identifier. If none can be found, the default value is returned.

    See

    Throws

    Error This exception is thrown if the container has been disposed.

  • Gets all instances registered in the container of the given service identifier. Used when service are defined with the { multiple: true } option.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to resolve.

    • recursive: boolean = true

    Returns null | T[]

    An array containing the service instances for the given identifier. If none can be found, null is returned.

    Example

    Here's an example:

    assert(container.getManyOrNull(UNKNOWN_TOKEN) === null);
    assert(Array.isArray(container.getManyOrNull(KNOWN_TOKEN)));

    See

    ContainerInstance.getMany

    Throws

    Error This exception is thrown if the container has been disposed.

  • Retrieves the service with given name or type from the service container. If the identifier cannot be found, return the provided default value.

    Type Parameters

    • U

      The type of the provided default value.

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to get the value of.

    • defaultValue: U
    • recursive: boolean = true

    Returns U | T

    The resolved value for the given metadata, or the default value if it could not be found.

    See

    ContainerInstance.getOrNull

    Throws

    Error This exception is thrown if the container has been disposed.

  • Retrieves the service with given name or type from the service container. Optionally, parameters can be passed in case if instance is initialized in the container for the first time.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to get the value of.

    • recursive: boolean = true

    Returns null | T

    The resolved value for the given metadata, or null if it could not be found.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Checks if the service with given name or type is registered service container. Optionally, parameters can be passed in case if instance is initialized in the container for the first time.

    If recursive mode is enabled, the symbol is not available locally, and we have a parent, we tell the parent to search its tree recursively too. If the container tree is substantial, this operation may affect performance.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier of the service to look up.

    • Optional recursive: boolean = true

      Whether the operation will be recursive.

    Returns boolean

    Whether the identifier is present in the current container, or its parent.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Gets a separate container instance for the given instance id.

    Type Parameters

    Parameters

    • Optional containerId: ContainerIdentifier

      The ID of the container to resolve or create. Defaults to "default".

    • Optional options: TOptions

    Returns CreateContainerResult<TOptions>

    The newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.

    Example

    const newContainer = Container.of('foo');

    @Service({ container: newContainer }, [])
    class MyService {}
  • Create a registry with the specified ID, with this instance as its parent.

    Type Parameters

    Parameters

    • Optional containerId: ContainerIdentifier

      The ID of the container to resolve or create. Defaults to "default".

    • Optional options: TOptions

    Returns CreateContainerResult<TOptions>

    The newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Removes services with the given list of service identifiers.

    Parameters

    Returns ContainerInstance

    The current ContainerInstance instance.

    Example

    Here's an example:

    const NAME = new Token<string>();

    // Set a new identifier in the container:
    defaultContainer.setValue(NAME, 'Joanna');
    assert(defaultContainer.get(NAME) === 'Joanna');

    // Now remove it, making the container forget it ever existed:
    defaultContainer.remove(NAME);
    assert(defaultContainer.getOrNull(NAME) === null);

    Throws

    Error This exception is thrown if the container has been disposed.

  • Resolve an identifier within the context of the current container, alongside a specific set of resolution constraints specified by the end-user.

    Parameters

    • identifier: ServiceIdentifier

      The identifier to resolve.

    • constraints: number

      The constraints to take into consideration while resolving the specified identifier.

    Returns unknown

    The result of resolving the value within the current container.

    Remarks

    If SkipSelf is specified, the parent of this container is used to resolve the identifier.

    See

    ResolutionConstraintFlag

    Throws

    ServiceNotFoundError This exception is thrown if an invalid identifier is provided, and the Optional flag has not been provided.

    Throws

    Error This exception is thrown if the SkipSelf constraint has been specified, but the current container does not have a parent.

    Throws

    Error This exception is thrown if SkipSelf and Self are used at the same time.

  • Resolve the metadata for the given identifier. Returns null if no metadata could be found.

    Type Parameters

    • T = unknown

    Parameters

    • identifier: ServiceIdentifier<T>

      The identifier to resolve metadata for.

    • recursive: boolean

      Whether the lookup operation is recursive.

    Returns null | readonly [ServiceMetadata<T>, ServiceIdentifierLocation]

    If the identifier is found, a tuple is returned consisting of the following:

    1. The metadata for the given identifier, if found.
    2. The location from where the metadata was returned. ServiceIdentifierLocation.Parent is returned if the identifier was found upstream.

    If an identifier cannot be found, null is returned.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Recursively check the presence of a multi-service identifier in the container hierarchy.

    Parameters

    • id: ServiceIdentifier

      The ID to lookup in the container hierarchy.

    • recursive: boolean = true

      Whether the operation will be performed recursively. If this is set to false, the identifier will only be looked up in the context of this container, regardless of whether the parent has the identifier.

    Returns MultiIDLookupResponse

    A tuple, with the first element specifying the location of the identifier (or ServiceIdentifierLocation.None | None if it wasn't found), with the second element being the value associated with the specified identifier.

    Example

    // Create a new container, as a child of a child of the default container.
    const myContainer = Container.ofChild(Symbol()).ofChild(Symbol());
    const MY_SERVICE = new Token<MyService>();

    // Add a service to the default container, as a value of the MY_SERVICE group.
    @Service({ container: myContainer, id: MY_SERVICE, multiple: true }, [ ])
    class MyService { }

    // Add another service to the default container, as a value of the MY_SERVICE group.
    Container.set({ id: MY_SERVICE, multiple: true, value: Symbol() });

    // Get the multi-IDs from the child container.
    const [myService, mySymbol] = myContainer.getMany(MY_SERVICE);

    Remarks

    This replaces the previous implementation, which did not implement proper recursion, as it only inherited from the direct container of a parent.

  • Resolve a Resolvable object in the current container.

    Parameters

    • resolvable: Resolvable

      The Resolvable to resolve.

    • guardBuiltIns: boolean

    Returns unknown

    The resolved value of the item.

  • Add a service to the container using the provided options, along with a pre-wrapped list of dependencies.

    This is mainly for internal use.

    Type Parameters

    • T = unknown

    Parameters

    • serviceOptions: Omit<ServiceOptions<T>, "dependencies">

      The options for the service to add to the container.

    • precompiledDependencies: Resolvable[]

      A precompiled list of dependencies in TypeWrapper form for the given service.

    Returns ServiceIdentifier

    The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.

    Throws

    Error This exception is thrown if the container has been disposed.

  • Add a service to the container using the provided options, containing all information about the new service including its dependencies.

    Type Parameters

    • T = unknown

    Parameters

    • serviceOptions: ServiceOptionsWithDependencies<T>

      The options for the service to add to the container.

    Returns ServiceIdentifier

    The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.

    Throws

    Error This exception is thrown if the container has been disposed.

    Throws

    CannotInstantiateBuiltInError This exception is thrown if the service references a built-in type, such as Number or String, without an accompanying factory. These are considered invalid, as the container has no way to instantiate them.

    Throws

    CannotInstantiateValueError This exception is thrown if a dependency of the service cannot be instantiated. A typeof check on a dependency should always result in one of the following:

    • "function": This would be for class or function-based services.
    • "string": Though discouraged, a string ServiceIdentifier can be used to reference a given dependency in the container.
    • "object": This could be a Token or anything else.
  • Add a service to the container, without providing any dependencies which would normally be required when initialising a service with a class-based ServiceOptions.type | .type member.

    Type Parameters

    • T = unknown

    Parameters

    • serviceOptions: ServiceOptionsWithoutTypeOrDependencies<T>

      The options for the service to add to the container. These options are expected to omit both the ServiceOptions.type | .type and .dependencies members.

    Returns ServiceIdentifier

    The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.

    Throws

    Error This exception is thrown if the container has been disposed.

    Throws

    CannotInstantiateBuiltInError This exception is thrown if the service references a built-in type, such as Number or String, without an accompanying factory. These are considered invalid, as the container has no way to instantiate them.

    Throws

    CannotInstantiateValueError This exception is thrown if a dependency of the service cannot be instantiated. A typeof check on a dependency should always result in one of the following:

    • "function": This would be for class or function-based services.
    • "string": Though discouraged, a string ServiceIdentifier can be used to reference a given dependency in the container.
    • "object": This could be a Token or anything else.
  • Add a value to the container.

    Type Parameters

    • TServiceID extends string | Token<TValue>

    • TValue extends unknown

    Parameters

    • id: TServiceID

      The ID of the new value to set inside the container. Must be either a string or a Token.

    • value: TValue

      The value to set the ID to.

    Returns ServiceIdentifier

    The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.

    Example

    // We can simplify this:
    Container.set({ id: 'key', value: 'test', dependencies: [ ] });
    // To this:
    Container.setValue('key', 'test');

    Throws

    Error This exception is thrown if the container has been disposed.

  • Gets a separate container instance for the given instance id. Optionally, a parent can be passed, which will act as an upstream resolver for the container.

    Type Parameters

    Parameters

    • containerId: ContainerIdentifier = 'default'

      The ID of the container to resolve or create. Defaults to "default".

    • parent: null | ContainerInstance = defaultContainer

      The parent of the container, or null to explicitly signal that one should not be provided. Defaults to the default container.

    • Optional options: TOptions

      The options to supplement how the container is created.

    Returns CreateContainerResult<TOptions>

    The newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.

    Remarks

    This is functionally equivalent to ContainerInstance.of. However, it allows container creation from a static interface.

    Example

    // Create a container which has the default container as its parent:
    ContainerInstance.of('my-new-container');

    // Create a container without a parent:
    ContainerInstance.of('my-new-container-without-a-parent', null);

    // Create a container with a separate container:
    ContainerInstance.of('my-new-special-container', myOtherContainer);

    See

    CreateContainerOptions

Generated using TypeDoc