Protected
constructorCreate a ContainerInstance.
The ID of the container to create.
Optional
parent: ContainerInstanceThe parent of the container to create. The parent is used for resolving identifiers which are not present in this container.
Readonly
disposedIndicates if the container has been disposed or not. Any function call should fail when called after being disposed.
This is readonly for outside consumers.
Its value will change to true
if the instance is disposed.
Readonly
idThe ID of this container. This will always be unique.
Private
isWhether 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 }
.
Private
Readonly
metadataMetadata for all registered services in this container.
Private
Readonly
multiServices 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.
Optional
Readonly
parentThe parent of the container to create. The parent is used for resolving identifiers which are not present in this container.
Private
visitorThe 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.
Static
Readonly
defaultThe default global container. By default services are registered into this
container when registered via Container.set()
or @Service
decorator.
Iterate over each service in the container.
Experimental
Add a visitor to the container.
The visitor to add to this container.
Whether the operation was successful.
Experimental
Remove a visitor from the container. No-op if the visitor was never attached to the container.
The visitor to remove from the container.
Whether the operation was successful.
Dispose the container, rendering it unable to perform any further injection or storage.
A promise that resolves when the disposal process is complete.
It is currently not advised to dispose of the default container. This would result in resolution issues in your application.
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')
);
Error This exception is thrown if the container has been disposed.
Private
disposeCheck if the given service is able to be destroyed and, if so, destroys it in-place.
the service metadata containing the instance to destroy
when true the service will be always destroyed even if it's cannot be re-created
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).
The identifier to get the value of.
Optional
recursive: booleanThe value of the identifier in the current scope.
ServiceNotFoundError This exception is thrown if the identifier cannot be found in the tree.
Error This exception is thrown if the container has been disposed.
Private
getProtected
getReturn 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.
The identifier of the service to look up.
A ServiceIdentifierLocation.
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.
The identifier to resolve.
Optional
recursive: booleanAn array containing the service instances for the given identifier.
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');
ServiceNotFoundError This exception is thrown if a value could not be found for the given identifier.
Error This exception is thrown if the container has been disposed.
Protected
getGets 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.
The type of the provided default value.
The identifier to resolve.
An array containing the service instances for the given identifier. If none can be found, the default value is returned.
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.
The identifier to resolve.
An array containing the service instances for the given identifier.
If none can be found, null
is returned.
Here's an example:
assert(container.getManyOrNull(UNKNOWN_TOKEN) === null);
assert(Array.isArray(container.getManyOrNull(KNOWN_TOKEN)));
Error This exception is thrown if the container has been disposed.
Protected
getRetrieves the service with given name or type from the service container. If the identifier cannot be found, return the provided default value.
The type of the provided default value.
The identifier to get the value of.
The resolved value for the given metadata, or the default value if it could not be found.
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.
The identifier to get the value of.
The resolved value for the given metadata, or null
if it could not be found.
Error This exception is thrown if the container has been disposed.
Private
getGets the value belonging to passed in ServiceMetadata instance.
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.
The identifier of the service to look up.
Optional
recursive: boolean = trueWhether the operation will be recursive.
Whether the identifier is present in the current container, or its parent.
Error This exception is thrown if the container has been disposed.
Gets a separate container instance for the given instance id.
Optional
containerId: ContainerIdentifierThe ID of the container to resolve or create. Defaults to "default".
Optional
options: TOptionsThe newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.
const newContainer = Container.of('foo');
@Service({ container: newContainer }, [])
class MyService {}
Create a registry with the specified ID, with this instance as its parent.
Optional
containerId: ContainerIdentifierThe ID of the container to resolve or create. Defaults to "default".
Optional
options: TOptionsThe newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.
Error This exception is thrown if the container has been disposed.
Removes services with the given list of service identifiers.
The list of service identifiers to remove from the container.
The current ContainerInstance instance.
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);
Error This exception is thrown if the container has been disposed.
Completely resets the container by removing all previously registered services from it.
Error This exception is thrown if the container has been disposed.
Protected
resolveResolve an identifier within the context of the current container, alongside a specific set of resolution constraints specified by the end-user.
The identifier to resolve.
The constraints to take into consideration while resolving the specified identifier.
The result of resolving the value within the current container.
If SkipSelf is specified, the parent of this container is used to resolve the identifier.
ServiceNotFoundError This exception is thrown if an invalid identifier is provided, and the Optional flag has not been provided.
Error This exception is thrown if the SkipSelf constraint has been specified, but the current container does not have a parent.
Error This exception is thrown if SkipSelf and Self are used at the same time.
Protected
resolveResolve the metadata for the given identifier. Returns null if no metadata could be found.
The identifier to resolve metadata for.
Whether the lookup operation is recursive.
If the identifier is found, a tuple is returned consisting of the following:
If an identifier cannot be found, null
is returned.
Error This exception is thrown if the container has been disposed.
Private
resolveRecursively check the presence of a multi-service identifier in the container hierarchy.
The ID to lookup in the container hierarchy.
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.
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.
// 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);
This replaces the previous implementation, which did not implement proper recursion, as it only inherited from the direct container of a parent.
Private
resolvePrivate
resolveAdd a service to the container using the provided options, along with a pre-wrapped list of dependencies.
This is mainly for internal use.
The options for the service to add to the container.
A precompiled list of dependencies in TypeWrapper form for the given service.
The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.
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.
The options for the service to add to the container.
The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.
Error This exception is thrown if the container has been disposed.
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.
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.
The options for the service to add to the container. These options are expected to omit both the ServiceOptions.type | .type and .dependencies members.
The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.
Error This exception is thrown if the container has been disposed.
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.
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.
The ID of the new value to set inside the container. Must be either a string or a Token.
The value to set the ID to.
The identifier of the given service in the container. This can then be passed to .get to resolve the identifier.
// We can simplify this:
Container.set({ id: 'key', value: 'test', dependencies: [ ] });
// To this:
Container.setValue('key', 'test');
Error This exception is thrown if the container has been disposed.
Static
ofGets 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.
The ID of the container to resolve or create. Defaults to "default".
The parent of the container, or null to explicitly signal that one should not be provided. Defaults to the default container.
Optional
options: TOptionsThe options to supplement how the container is created.
The newly-created ContainerInstance, or the pre-existing container with the same name if one already exists.
This is functionally equivalent to ContainerInstance.of. However, it allows container creation from a static interface.
// 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);
Generated using TypeDoc
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