Skip to content

Singletons

To maintain configuration and state, whilst making the API easy to use, singletons have been employed. This section will go demonstrate the usage of this pattern within the SDK and provide guidance on its use for development.

Registration

To use register a singleton for use, first it needs a factory function binding to the Container instance.

this.singleton('myclass', function (app: ContainerInterface, config: Config) {
return new MyClass();
});

Binding a factory function to the abstract key 'myclass'

The factory function takes two parameters, the Container instance and an instance of the Config bag. What is returned is known as the "Concrete" instance.

The "abstract" is the key that the binding will be accessible by. This should be a string that is unique to this factory.

Binding an abstract with a non-unique name will overwrite the previous factory

Resolution

Retrieving an instance from the Container is simple.

this.resolve<MyClass>('myclass');

Retrieving an instance of MyClass from the Container

When a Concrete instance is returned, it is stored within the Container against the abstract. The next time the resolve method is run, it will retrieve the concrete instance from the store.

Resetting

It is sometimes necessary to refresh a concrete instance.

this.resetInstance('myclass');

Resetting 'myclass'

Invoking resetInstance will clear the concrete instance from the store, and then invoke the associated factory.

Don't confuse resolveInstance and resolve. resolveInstance is a state method which can be used to resolve the active container for static methods.
static get MyClass(): MyClass {
return this.resolveInstance()
.resolve('myclass');
}

Resolving 'myclass' statically

Edit this page on GitHub
1 contributorSmudge3806
Last edited by Smudge3806 on June 4, 2020