Class: Container
The dependency injection container: it registers the classes of the objects (components, providers, modules, any BaseObject), creates them on demand with their lifetime and destroys them with itself.
An object is created asynchronously: its @Inject properties are resolved from the container, its @Configurable properties get their configured values (validated and transformed by their schemas), then its init() runs; the promise of get(), set() or build() settles once init() has completed. The lifetime of the class decides which instance is returned:
@Singleton(components, modules): one instance, held by the container which registered the class.@Scoped(providers): one instance per scope (see Container.createScope), such as per request.@Transient(BaseObject): a new instance on each request.
The applications rarely create a container: the Application owns the root one, each object owns a child container tracking the objects it creates (destroyed with it), and the modules and components reach theirs through their protected container property. A container created with new Container() is a root container, to use the objects without an application (tests, scripts).
Example
import {Component, Container, DTO, Provider} from 'lakutata'
import {Configurable, Inject} from 'lakutata/decorator/di'
class Greeter extends Provider {
//'Hello' unless configured
@Configurable(DTO.String())
protected readonly greeting: string = 'Hello'
public greet(name: string): string {
return `${this.greeting}, ${name}`
}
}
class Reception extends Component {
@Inject('greeter')
protected readonly greeter!: Greeter
public welcome(name: string): string {
return this.greeter.greet(name)
}
}
const container: Container = new Container()
await container.registerNamed('greeter', Greeter, {greeting: 'Welcome'})
const reception: Reception = await container.set(Reception)
console.log(reception.welcome('Ada')) //Welcome, Ada
await container.destroy()Constructors
Constructor
new Container(
parent?,owner?):Container
Create a container. Without parent, a root container; with a parent, a container whose registrations fall back to the parent's, destroyed together with it.
Parameters
parent?
Container
The parent container, none for a root container.
owner?
The object owning the container (the framework gives each object its own container).
Returns
Container
Properties
parent?
readonlyoptionalparent?:Container
The container this one was created from (the one of the object which created the owner, or the one a scope was created from); undefined for a root container.
Methods
build()
build<
T>(target,configurableRecords?):Promise<T>
Create a new object of a class without registering it, whatever its lifetime: its dependencies are injected from this container, and it is destroyed with this container (unless disposed before).
Type Parameters
T
T extends BaseObject
Parameters
target
The class, registered or not.
configurableRecords?
Record<string, any>
The options of the object.
Returns
Promise<T>
The new object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the object fails to be created.
clear()
clear():
Promise<void>
Destroy the container's objects and scopes, the container remaining usable: the teardown hooks run (the entrypoints stop), then the scopes and the containers of the objects are destroyed, then the cached objects and the transient objects still alive. Never throws: the errors are reported through the application's logger, and a failing object does not stop the teardown of the others.
Returns
Promise<void>
Resolves once everything is destroyed.
createScope()
createScope():
Container
Create a scope: a child container holding its own instances of the scoped objects (one per scope, such as one per request), the singletons and registrations of this container being shared. The scope lives until it is destroyed explicitly, or together with this container.
Returns
Container
The new scope.
Throws
When the container has been destroyed.
destroy()
destroy():
Promise<void>
Destroy the container: as Container.clear, then the container refuses any further request with an ObjectDestroyedException. A concurrent or repeated call waits for the same teardown.
Returns
Promise<void>
Resolves once the container is destroyed.
forget()
forget(
name,instance):void
Drop the cached instance of a registration, so the next request creates a new one; nothing happens when the cached instance is not the one given.
Parameters
name
string | symbol
The registration name or symbol.
instance
The instance to drop.
Returns
void
get()
Call Signature
get<
T>(constructor,configurableRecords?):Promise<T>
Get an object registered by its class, creating it when the lifetime requires: a singleton is created once, a scoped object once per scope, a transient object on each call. A class marked @Autoload is registered on first request (its singleton in the root container, its scoped object in the nearest scope). A scoped object requested with options is a new instance owned by the caller, not the one shared within the scope (see Container.getShared).
Type Parameters
T
T extends BaseObject
Parameters
constructor
The class the object was registered with (an object registered under a name is not found by its class).
configurableRecords?
Record<string, any>
The options of the object (the values of its @Configurable properties and the options it reads), merged over the ones it was registered with; validated when the object is created. Ignored, with a warning outside production, when the cached singleton or scoped instance already exists.
Returns
Promise<T>
The object, once its dependencies are injected, its options applied and its init() completed.
Throws
When the container has been destroyed.
Throws
When the class is not registered here or in a parent container, or the object fails to be created (an injection failing with a DependencyInjectionException, an invalid option, an error of init()).
Call Signature
get<
T>(name,configurableRecords?):Promise<T>
Get an object registered under a name, as Container.get by class.
Type Parameters
T
T extends BaseObject
Parameters
name
string
The name the object was registered under (its key in the module options).
configurableRecords?
Record<string, any>
The options of the object (the values of its @Configurable properties and the options it reads), merged over the ones it was registered with; validated when the object is created. Ignored, with a warning outside production, when the cached singleton or scoped instance already exists.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the name is not registered, or the object fails to be created.
Call Signature
get<
T>(name,configurableRecords?):Promise<T>
Get an object registered under a symbol, as Container.get by class.
Type Parameters
T
T extends BaseObject
Parameters
name
symbol
The symbol the object was registered under.
configurableRecords?
Record<string, any>
The options of the object (the values of its @Configurable properties and the options it reads), merged over the ones it was registered with; validated when the object is created. Ignored, with a warning outside production, when the cached singleton or scoped instance already exists.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the symbol is not registered, or the object fails to be created.
Call Signature
get<
T>(name,configurableRecords?):Promise<T>
Get an object registered under a name or a symbol, as Container.get by class.
Type Parameters
T
T extends BaseObject
Parameters
name
string | symbol
The name or symbol the object was registered under.
configurableRecords?
Record<string, any>
The options of the object (the values of its @Configurable properties and the options it reads), merged over the ones it was registered with; validated when the object is created. Ignored, with a warning outside production, when the cached singleton or scoped instance already exists.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the name is not registered, or the object fails to be created.
Call Signature
get<
T>(nameOrConstructor,configurableRecords?):Promise<T>
Get an object registered under a name, a symbol or by its class, as Container.get by class.
Type Parameters
T
T extends BaseObject
Parameters
nameOrConstructor
string | symbol | IBaseObjectConstructor<T>
The name, symbol or class the object was registered with.
configurableRecords?
Record<string, any>
The options of the object (the values of its @Configurable properties and the options it reads), merged over the ones it was registered with; validated when the object is created. Ignored, with a warning outside production, when the cached singleton or scoped instance already exists.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When it is not registered, or the object fails to be created.
getShared()
Call Signature
getShared<
T>(constructor,configurableRecords?):Promise<T>
Get the shared instance of an object registered by its class (the container's instance, or the scope's instance for a scoped object), created with the options when it does not exist yet. Unlike Container.get, a scoped object requested with options is not a new instance owned by the caller: the creator of a scope uses it to provide an object configured for the request, which the request's objects then share.
Type Parameters
T
T extends BaseObject
Parameters
constructor
The class the object was registered with.
configurableRecords?
Record<string, any>
The options of the object, used only when the shared instance is created now; ignored, with a warning outside production, when it exists already.
Returns
Promise<T>
The shared object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the class is not registered, or the object fails to be created.
Call Signature
getShared<
T>(name,configurableRecords?):Promise<T>
Get the shared instance of an object registered under a name or a symbol, as Container.getShared by class.
Type Parameters
T
T extends BaseObject
Parameters
name
string | symbol
The name or symbol the object was registered under.
configurableRecords?
Record<string, any>
The options of the object, used only when the shared instance is created now.
Returns
Promise<T>
The shared object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the name is not registered, or the object fails to be created.
has()
Call Signature
has(
symbol):boolean
Whether an object is registered under a symbol, in this container or one of its parents.
Parameters
symbol
symbol
The registration symbol.
Returns
boolean
true when registered.
Call Signature
has(
name):boolean
Whether an object is registered under a name, in this container or one of its parents.
Parameters
name
string
The registration name.
Returns
boolean
true when registered.
Call Signature
has(
nameOrSymbol):boolean
Whether an object is registered under a name or a symbol, in this container or one of its parents.
Parameters
nameOrSymbol
string | symbol
The registration name or symbol.
Returns
boolean
true when registered.
Call Signature
has<
ClassConstructor>(constructor):boolean
Whether a class is registered by its class (not under a name), in this container or one of its parents; an @Autoload class not requested yet is not registered.
Type Parameters
ClassConstructor
ClassConstructor extends typeof BaseObject
Parameters
constructor
ClassConstructor
The class.
Returns
boolean
true when registered.
load()
load<
T>(options):Promise<void>
Register objects in the container, without creating them: a class is registered under the symbol of its class (got by its class), a declaration with an id under its id (got by its name) with its options, a glob pattern registers the classes of the files it matches. A name registered again replaces the previous registration.
Type Parameters
T
T extends typeof BaseObject
Parameters
options
(string | typeof BaseObject | LoadObjectOptions<typeof BaseObject>)[]
The classes, declarations ({class, ...options}) and glob patterns to register.
Returns
Promise<void>
Resolves once registered (the glob patterns imported).
Throws
When an item is neither a class, a declaration nor a glob pattern.
Throws
When the container has been destroyed.
Throws
When a file matched by a glob pattern fails to import.
owner()
owner<
Owner>():Owner|undefined
The object owning the container (the one whose container it is, or the owner of the container a scope was created from).
Type Parameters
Owner
Owner extends BaseObject = BaseObject
Returns
Owner | undefined
The owner, or undefined for a container without owner or whose owner was garbage collected.
register()
register<
T>(target,configurableRecords?):Promise<void>
Register a class by its class, without creating its object; a class registered again replaces its previous registration.
Type Parameters
T
T extends BaseObject
Parameters
target
The class.
configurableRecords?
Record<string, any>
The options its objects are created with.
Returns
Promise<void>
Resolves once registered.
Throws
When the container has been destroyed.
registerContainerToItsParent()
registerContainerToItsParent():
void
Track this container in its parent again, so it is destroyed together with the parent (used when its owner is initialized again).
Returns
void
registerNamed()
registerNamed<
T>(name,target,configurableRecords?):Promise<void>
Register a class under a name, without creating its object; a name registered again replaces its previous registration.
Type Parameters
T
T extends BaseObject
Parameters
name
string | symbol
The registration name or symbol.
target
The class.
configurableRecords?
Record<string, any>
The options its objects are created with.
Returns
Promise<void>
Resolves once registered.
Throws
When the container has been destroyed.
revive()
revive():
void
Make a destroyed container usable again, when its owner is reloaded.
Returns
void
Throws
When the parent container has been destroyed (or is being destroyed).
set()
set<
T>(target,configurableRecords?):Promise<T>
Register a class (unless it is registered already) and get its object, as Container.get.
Type Parameters
T
T extends BaseObject
Parameters
target
The class.
configurableRecords?
Record<string, any>
The options of the object: registered with the class when it is registered now, and requested for the object.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the object fails to be created.
setNamed()
setNamed<
T>(name,target,configurableRecords?):Promise<T>
Register a class under a name, replacing a previous registration of the name, and get its object.
Type Parameters
T
T extends BaseObject
Parameters
name
string | symbol
The registration name or symbol.
target
The class.
configurableRecords?
Record<string, any>
The options the object is registered with.
Returns
Promise<T>
The object, once created and initialized.
Throws
When the container has been destroyed.
Throws
When the object fails to be created.