@adrianhelvik/container
A non-hacky dependency container with lazily created dependencies.
API
Container.prototype.provider(name: string, provider: function)
Adds a new value to the container in the form of a provider function. The provider is called with the dependencies in the container.
Container.prototype.constant(name: string, value: any)
Adds a new value to the container in the form of a constant value.
Container.prototype.invoke(fn: function)
Invoke the given function with the dependencies in the container. This method creates a new container, so that we can use the provide method as well.
const container = containercontainer container
Injected: invoke
The invoke function is injected. It allows you to invoke another function with the dependencies of the container as the first parameter. A new child container is created to allow providing scoped dependencies.
Injected: provide
This method lets you provide a dependency into the container.
It calls .constant(k, v)
on the current container.
container
Container.prototype.extend()
Create a container that extends from the current one. Dependencies from the child container are preferred. The child container will lookup dependencies in the parent container if no matching dependency is found in the parent container.
const container = containerconst childContainer = containerchildContainer childContainer childContainer childContainer
Container.prototype.keys()
Returns the names of the dependencies in the current container. Does not include the keys of any parent container.
containerconst childContainer = containerchildContainer
Container.prototype.get(key)
Gets a given property from the container.
const container = container
Container.prototype.has(key)
Checks if a property exists in the container. Does not invoke provider functions and returns true even if the value in the container is undefined. This checks for the value in parent containers as well.
const container = let calledcontainer
Container.prototype.hasOwn(key)
Checks if a property exists in the container. Does not invoke provider functions and returns true even if the value in the container is undefined. Does NOT check parent containers for the key.
const container = const child = containercontainer
Cyclic dependencies
Cyclic dependencies can be resolved with the invoke function. It is however a very good idea to prevent cyclic dependencies in the first place.
An important note here is that the provider function must return before invoking the cyclic dependency. This could be done either as in the example below, by making the values in the container be promises, or by having the values be functions, where invoke is used in the body of the returned function.
But as a general rule of thumb: Avoid cyclic dependencies
Good example
container container container
Bad example
container container
Example
const container = container container // The dependency 'foo' is now injected into// the function and the provider for foo is// called.container