Enumeration: BindingScope

Scope for binding values

Members
Name Default Value Flags Description
CONTEXT "Context" exported

The binding provides a value as a singleton within each local context. The value is calculated only once per context and cached for subsequential uses. Child contexts have their own value and do not share with their ancestors.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2
  1. 0 is the resolved value for 'b1' within the app afterward
  • app.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app but not in req1, a new value 1 is calculated and used for req1 afterward
  • req1.get('b1') ==> 1 (always)
  1. 'b1' is resolved in app but not in req2, a new value 2 is calculated and used for req2 afterward
  • req2.get('b1') ==> 2 (always)

SINGLETON "Singleton" exported

The binding provides a value as a singleton within the context hierarchy (the owning context and its descendants). The value is calculated only once for the owning context and cached for subsequential uses. Child contexts share the same value as their ancestors.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2
  1. 0 is the singleton for app afterward
  • app.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app, reuse it for req1
  • req1.get('b1') ==> 0 (always)
  1. 'b1' is resolved in app, reuse it for req2
  • req2.get('b1') ==> 0 (always)

TRANSIENT "Transient" exported

The binding provides a value that is calculated each time. This will be the default scope if not set.

For example, with the following context hierarchy:

  • app (with a binding 'b1' that produces sequential values 0, 1, ...)
    • req1
    • req2

Now 'b1' is resolved to a new value each time for app and its descendants req1 and req2:

  • app.get('b1') ==> 0
  • req1.get('b1') ==> 1
  • req2.get('b1') ==> 2
  • req2.get('b1') ==> 3
  • app.get('b1') ==> 4

Enumeration: BindingType

Type of the binding source

Members
Name Default Value Flags Description
ALIAS "Alias" exported

A alias to another binding key with optional path

CLASS "Class" exported

A class to be instantiated as the value

CONSTANT "Constant" exported

A fixed value

DYNAMIC_VALUE "DynamicValue" exported

A function to get the value

PROVIDER "Provider" exported

A provider class with value() function to get the value

Class: binding = new Binding()

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

Properties
Name Type Default Value Flags Description
isLocked boolean public exported constructorProperty

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

key string public exported

Key of the binding

tagMap TagMap public exported

Map for tag name/value pairs

constructor(key: string, isLocked: boolean) : Binding

Parameters
Name Type Default Value Flags Description
key string

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

isLocked boolean false

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

scope() :

tagNames() :

type() :

valueConstructor() :

apply(templateFn: BindingTemplate<T>) : this

Apply a template function to set up the binding with scope, tags, and other attributes as a group.

For example,

const serverTemplate = (binding: Binding) =>
  binding.inScope(BindingScope.SINGLETON).tag('server');

const serverBinding = new Binding<RestServer>('servers.RestServer1'); serverBinding.apply(serverTemplate);

Parameters
Name Type Default Value Flags Description
templateFn BindingTemplate<T>

A function to configure the binding

applyDefaultScope(scope: BindingScope) : this

Apply default scope to the binding. It only changes the scope if it's not set yet

Parameters
Name Type Default Value Flags Description
scope BindingScope

Default binding scope

getValue(ctx: Context, session: ResolutionSession) : ValueOrPromise<T>

This is an internal function optimized for performance. Users should use @inject(key) or ctx.get(key) instead.

Get the value bound to this key. Depending on isSync, this function returns either:

  • the bound value
  • a promise of the bound value

Consumers wishing to consume sync values directly should use isPromise to check the type of the returned value to decide how to handle it.

const result = binding.getValue(ctx);
if (isPromiseLike(result)) {
  result.then(doSomething)
} else {
  doSomething(result);
}

Parameters
Name Type Default Value Flags Description
ctx Context

Context for the resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

getValue(ctx: Context, options: ResolutionOptions) : ValueOrPromise<T | undefined>

Returns a value or promise for this binding in the given context. The resolved value can be undefined if optional is set to true in options.

Parameters
Name Type Default Value Flags Description
ctx Context

Context for the resolution

options ResolutionOptions optional

Optional options for binding and dependency resolution

inScope(scope: BindingScope) : this

Set the binding scope

Parameters
Name Type Default Value Flags Description
scope BindingScope

Binding scope

lock() : this

tag(tags: BindingTag[]) : this

Tag the binding with names or name/value objects. A tag has a name and an optional value. If not supplied, the tag name is used as the value.

Parameters
Name Type Default Value Flags Description
tags BindingTag[] rest

A list of names or name/value objects. Each parameter can be in one of the following forms:

  • string: A tag name without value
  • string[]: An array of tag names
  • TagMap: A map of tag name/value pairs

to(value: T) : this

Bind the key to a constant value. The value must be already available at binding time, it is not allowed to pass a Promise instance.

Parameters
Name Type Default Value Flags Description
value T

The bound value.

toAlias(keyWithPath: BindingAddress<T>) : this

Bind the key to an alias of another binding

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<T>

Target binding key with optional path, such as servers.RestServer.options#apiExplorer

toClass(ctor: Constructor<T>) : this

Bind the key to an instance of the given class.

Parameters
Name Type Default Value Flags Description
ctor Constructor<T>

The class constructor to call. Any constructor arguments must be annotated with @inject so that we can resolve them from the context.

toDynamicValue(factoryFn: () => ValueOrPromise<T>) : this

Bind the key to a computed (dynamic) value.

Parameters
Name Type Default Value Flags Description
factoryFn anonymous

The factory function creating the value. Both sync and async functions are supported.

toJSON() : Object

toProvider(providerClass: Constructor<Provider<T>>) : this

Bind the key to a value computed by a Provider.

  • @example
export class DateProvider implements Provider<Date> {
  constructor(@inject('stringDate') private param: String){}
  value(): Date {
    return new Date(param);
  }
}

Parameters
Name Type Default Value Flags Description
providerClass Constructor<Provider<T>>

Binding represents an entry in the Context. Each binding has a key and a corresponding value getter.

unlock() : this

Unlock the binding

bind(key: BindingAddress<T>) : Binding<T>

A static method to create a binding so that we can do Binding.bind('foo').to('bar'); as new Binding('foo').to('bar') is not easy to read.

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding key

Type alias: BindingTemplate(binding: Binding<T>): void

A function as the template to configure bindings

Arguments
Name Type Description
binding Binding<T>

Type alias: TagMap = MapObject

Namespace: bind

Function: bind.provider

bind.provider(specs: BindingSpec[]) : anonymous

@bind.provider to denote a provider class

A list of binding scope/tags or template functions to configure the binding

Parameters
Name Type Default Value Flags Description
specs BindingSpec[] rest

Type alias: BindingFilter(binding: Readonly<Binding<ValueType>>): boolean

A function that filters bindings. It returns true to select a given binding.

Arguments
Name Type Description
binding Readonly<Binding<ValueType>>

Function: filterByKey

filterByKey(keyPattern: string | RegExp | BindingFilter) : BindingFilter

Create a binding filter from key pattern

Parameters
Name Type Default Value Flags Description
keyPattern string | RegExp | BindingFilter optional

Binding key/wildcard, regexp, or a filter function

Function: filterByTag

filterByTag(tagPattern: BindingTag | RegExp) : BindingFilter

Create a binding filter for the tag pattern

Parameters
Name Type Default Value Flags Description
tagPattern BindingTag | RegExp

Binding tag name, regexp, or object

Function: isBindingAddress

isBindingAddress(bindingSelector: BindingSelector) : boolean

Type guard for binding address

Parameters
Name Type Default Value Flags Description
bindingSelector BindingSelector

Type alias: TypeNamespaceMapping(name: string): string

Mapping artifact types to binding key namespaces (prefixes). For example:

{
  repository: 'repositories'
}

Arguments
Name Type Description
name string

const BINDING_METADATA_KEY = MetadataAccessor.create< BindingMetadata, ClassDecorator >('binding.metadata')

Metadata key for binding metadata

Function: asBindingTemplate

asBindingTemplate(scopeAndTags: BindingScopeAndTags) : BindingTemplate

Convert binding scope and tags as a template function

Parameters
Name Type Default Value Flags Description
scopeAndTags BindingScopeAndTags

Binding scope and tags

Function: asClassOrProvider

asClassOrProvider(target: Constructor<unknown>) : BindingTemplate

A factory function to create a template function to bind the target class as a class or Provider.

Parameters
Name Type Default Value Flags Description
target Constructor<unknown>

Target class, which can be an implementation of Provider

Function: asProvider

asProvider(target: Constructor<Provider<unknown>>) : BindingTemplate

A factory function to create a template function to bind the target class as a Provider.

Parameters
Name Type Default Value Flags Description
target Constructor<Provider<unknown>>

Target provider class

Function: bindingTemplateFor

bindingTemplateFor(cls: Constructor<T | Provider<T>>) : BindingTemplate<T>

Get the binding template for a class with binding metadata

Parameters
Name Type Default Value Flags Description
cls Constructor<T | Provider<T>>

A class with optional @bind

Function: createBindingFromClass

createBindingFromClass(cls: Constructor<T | Provider<T>>, options: BindingFromClassOptions) : Binding<T>

Create a binding from a class with decorated metadata. The class is attached to the binding as follows:

  • binding.toClass(cls): if cls is a plain class such as MyController
  • binding.toProvider(cls): it cls is a value provider class with a prototype method value()

Parameters
Name Type Default Value Flags Description
cls Constructor<T | Provider<T>>

A class. It can be either a plain class or a value provider class

options BindingFromClassOptions {}

Options to customize the binding key

Function: getBindingMetadata

getBindingMetadata(target: Function) : BindingMetadata | undefined

Get binding metadata for a class

Parameters
Name Type Default Value Flags Description
target Function

The target class

Function: isProviderClass

isProviderClass(cls: Constructor<unknown>) : boolean

Check if a class implements Provider interface

Parameters
Name Type Default Value Flags Description
cls Constructor<unknown>

A class

Function: removeNameAndKeyTags

removeNameAndKeyTags(binding: Binding<unknown>) : void

A binding template function to delete name and key tags

Parameters
Name Type Default Value Flags Description
binding Binding<unknown>

Object literal: DEFAULT_TYPE_NAMESPACES

Variables
Name Type Default Value Flags Description
class string "classes" exported
provider string "providers" exported

Class: bindingkey = new BindingKey()

Properties
Name Type Default Value Flags Description
PROPERTY_SEPARATOR "#" static exported

deepProperty(propertyPath: string) : BindingKey<PropertyValueType>

Get a binding address for retrieving a deep property of the object bound to the current binding key.

Parameters
Name Type Default Value Flags Description
propertyPath string

A dot-separated path to a (deep) property, e.g. "server.port".

toString() : string

create(key: string, propertyPath: undefined | string) : BindingKey<ValueType>

Create a new key for a binding bound to a value of type ValueType.

Example

BindingKey.create<string>('application.name');
BindingKey.create<number>('config', 'rest.port);
BindingKey.create<number>('config#rest.port');

Parameters
Name Type Default Value Flags Description
key string

The binding key. When propertyPath is not provided, the key is allowed to contain propertyPath as encoded via BindingKey#toString()

propertyPath undefined | string optional

Optional path to a deep property of the bound value.

parseKeyWithPath(keyWithPath: BindingAddress<T>) : BindingKey<T>

Parse a string containing both the binding key and the path to the deeply nested property to retrieve.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<T>

The key with an optional path, e.g. "application.instance" or "config#rest.port".

validate(key: BindingAddress<T>) : string

Validate the binding key format. Please note that # is reserved. Returns a string representation of the binding key.

Parameters
Name Type Default Value Flags Description
key BindingAddress<T>

Binding key, such as a, a.b, a:b, or a/b

Class: context = new Context()

Context provides an implementation of Inversion of Control (IoC) container

Properties
Name Type Default Value Flags Description
name string exported

Name of the context

constructor(_parent: Context | string, name: undefined | string) : Context

Create a new context. For example, ```ts // Create a new root context, let the framework to create a unique name const rootCtx = new Context();

// Create a new child context inheriting bindings from rootCtx const childCtx = new Context(rootCtx);

// Create another root context called "application" const appCtx = new Context('application');

// Create a new child context called "request" and inheriting bindings // from appCtx const reqCtx = new Context(appCtx, 'request'); ```

Parameters
Name Type Default Value Flags Description
_parent Context | string optional

The optional parent context

name undefined | string optional

Name of the context, if not provided, a uuid will be generated as the name

add(binding: Binding<unknown>) : this

Add a binding to the context. If a locked binding already exists with the same key, an error will be thrown.

Parameters
Name Type Default Value Flags Description
binding Binding<unknown>

The configured binding to be added

bind(key: BindingAddress<ValueType>) : Binding<ValueType>

Create a binding with the given key in the context. If a locked binding already exists with the same key, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

close() : void

Close the context and release references to other objects in the context chain.

This method MUST be called to avoid memory leaks once a context object is no longer needed and should be recycled. An example is the RequestContext, which is created per request.

contains(key: BindingAddress) : boolean

Check if a binding exists with the given key in the local context without delegating to the parent context

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

createView(filter: BindingFilter) : ContextView<T>

Create a view of the context chain with the given binding filter

Parameters
Name Type Default Value Flags Description
filter BindingFilter

A function to match bindings

find(pattern: string | RegExp | BindingFilter) : Readonly<Binding<ValueType>>[]

Find bindings using a key pattern or filter function

Parameters
Name Type Default Value Flags Description
pattern string | RegExp | BindingFilter optional

A filter function, a regexp or a wildcard pattern with optional * and ?. Find returns such bindings where the key matches the provided pattern.

For a wildcard:

  • * matches zero or more characters except . and :
  • ? matches exactly one character except . and :

For a filter function:

  • return true to include the binding in the results
  • return false to exclude it.

findByTag(tagFilter: BindingTag | RegExp) : Readonly<Binding<ValueType>>[]

Find bindings using the tag filter. If the filter matches one of the binding tags, the binding is included.

Parameters
Name Type Default Value Flags Description
tagFilter BindingTag | RegExp

A filter for tags. It can be in one of the following forms:

  • A regular expression, such as /controller/
  • A wildcard pattern string with optional * and ?, such as 'con*' For a wildcard:
    • * matches zero or more characters except . and :
    • ? matches exactly one character except . and :
  • An object containing tag name/value pairs, such as {name: 'my-controller'}

get(keyWithPath: BindingAddress<ValueType>, session: ResolutionSession) : Promise<ValueType>

Get the value bound to the given key, throw an error when no value is bound for the given key.

Returns:

A promise of the bound value.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

session ResolutionSession optional

Optional session for resolution (accepted for backward compatibility)

get(keyWithPath: BindingAddress<ValueType>, options: ResolutionOptions) : Promise<ValueType | undefined>

Get the value bound to the given key, optionally return a (deep) property of the bound value.

Returns:

A promise of the bound value, or a promise of undefined when the optional binding is not found.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

options ResolutionOptions

Options for resolution.

getBinding(key: BindingAddress<ValueType>) : Binding<ValueType>

Look up a binding by key in the context and its ancestors. If no matching binding is found, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

getBinding(key: BindingAddress<ValueType>, options: undefined | anonymous) : Binding<ValueType> | undefined

Look up a binding by key in the context and its ancestors. If no matching binding is found and options.optional is not set to true, an error will be thrown.

Parameters
Name Type Default Value Flags Description
key BindingAddress<ValueType>

Binding key

options undefined | anonymous optional

Options to control if the binding is optional. If `options.optional` is set to true, the method will return `undefined` instead of throwing an error if the binding key is not found.

getOwnerContext(key: BindingAddress) : Context | undefined

Get the owning context for a binding key

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

getSync(keyWithPath: BindingAddress<ValueType>, session: ResolutionSession) : ValueType

Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.

This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.

Returns:

A promise of the bound value.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

session ResolutionSession optional

Session for resolution (accepted for backward compatibility)

getSync(keyWithPath: BindingAddress<ValueType>, options: ResolutionOptions) : ValueType | undefined

Get the synchronous value bound to the given key, optionally return a (deep) property of the bound value.

This method throws an error if the bound value requires async computation (returns a promise). You should never rely on sync bindings in production code.

Returns:

The bound value, or undefined when an optional binding is not found.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

options ResolutionOptions optional

Options for resolution.

getValueOrPromise(keyWithPath: BindingAddress<ValueType>, optionsOrSession: ResolutionOptionsOrSession) : ValueOrPromise<ValueType | undefined>

Get the value bound to the given key.

This is an internal version that preserves the dual sync/async result of Binding#getValue(). Users should use get() or getSync() instead.

Returns:

The bound value or a promise of the bound value, depending on how the binding is configured.

Parameters
Name Type Default Value Flags Description
keyWithPath BindingAddress<ValueType>

The binding key, optionally suffixed with a path to the (deeply) nested property to retrieve.

optionsOrSession ResolutionOptionsOrSession optional

Options for resolution or a session

isBound(key: BindingAddress) : boolean

Check if a key is bound in the context or its ancestors

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

isSubscribed(observer: ContextObserver) : boolean

Check if an observer is subscribed to this context

Parameters
Name Type Default Value Flags Description
observer ContextObserver

Context observer

subscribe(observer: ContextEventObserver) : Subscription

Add a context event observer to the context

Parameters
Name Type Default Value Flags Description
observer ContextEventObserver

Context observer instance or function

toJSON() : Object

Create a plain JSON object for the context

unbind(key: BindingAddress) : boolean

Unbind a binding from the context. No parent contexts will be checked. If you need to unbind a binding owned by a parent context, use the code below:

const ownerCtx = ctx.getOwnerContext(key);
return ownerCtx != null && ownerCtx.unbind(key);

Returns:

true if the binding key is found and removed from this context

Parameters
Name Type Default Value Flags Description
key BindingAddress

Binding key

unsubscribe(observer: ContextEventObserver) : boolean

Remove the context event observer from the context

Parameters
Name Type Default Value Flags Description
observer ContextEventObserver

Context event observer

Interface: ContextObserver

Observers of context bind/unbind events

Properties
Name Type Default Value Flags Description
filter BindingFilter exported optional

An optional filter function to match bindings. If not present, the listener will be notified of all binding events.

observe ContextObserverFn exported

Listen on bind, unbind, or other events

Interface: Subscription

Subscription of context events. It's modeled after https://github.com/tc39/proposal-observable.

Properties
Name Type Default Value Flags Description
closed boolean exported

Is the subscription closed?

unsubscribe() : void

unsubscribe

Type alias: ContextObserverFn(eventType: ContextEventType, binding: Readonly<Binding<unknown>>, context: Context): ValueOrPromise

Listen on bind, unbind, or other events

Returns:

Arguments
Name Type Description
eventType ContextEventType

Context event type

binding Readonly<Binding<unknown>>

The binding as event source

context Context

Context object for the binding event

Class: contextview = new ContextView()

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

Properties
Name Type Default Value Flags Description
filter BindingFilter<T> public exported constructorProperty

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

constructor(context: Context, filter: BindingFilter<T>) : ContextView

Parameters
Name Type Default Value Flags Description
context Context

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

filter BindingFilter<T>

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

bindings() :

asGetter(session: ResolutionSession) : Getter<T[]>

As a Getter function

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

close() : void

Stop listening events from the context

observe(event: ContextEventType, binding: Readonly<Binding<unknown>>) : void

Listen on bind or unbind and invalidate the cache

Parameters
Name Type Default Value Flags Description
event ContextEventType

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

binding Readonly<Binding<unknown>>

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

open() : undefined | Subscription

Start listening events from the context

refresh() : void

Refresh the view by invalidating its cache

resolve(session: ResolutionSession) : ValueOrPromise<T[]>

Resolve values for the matching bindings

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

Resolution session

values(session: ResolutionSession) : Promise<T[]>

Get the list of resolved values. If they are not cached, it tries to find and resolve them.

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

ContextView provides a view for a given context chain to maintain a live list of matching bindings and their resolved values within the context hierarchy.

This class is the key utility to implement dynamic extensions for extension points. For example, the RestServer can react to controller bindings even they are added/removed/updated after the application starts.

ContextView is an event emitter that emits the following events:

  • 'close': when the view is closed (stopped observing context events)
  • 'refresh': when the view is refreshed as bindings are added/removed
  • 'resolve': when the cached values are resolved and updated

Function: createViewGetter

createViewGetter(ctx: Context, bindingFilter: BindingFilter<T>, session: ResolutionSession) : Getter<T[]>

Create a context view as a getter

Parameters
Name Type Default Value Flags Description
ctx Context

Context object

bindingFilter BindingFilter<T>

A function to match bindings

session ResolutionSession optional

Resolution session

Namespace: Getter

The function injected by @inject.getter(bindingSelector).

Function: Getter.fromValue

Getter.fromValue(value: T) : Getter<T>

Convert a value into a Getter returning that value.

Parameters
Name Type Default Value Flags Description
value T

Namespace: inject

Function: inject.context

inject.context() : markParameterOrPropertyAsInjected

Inject the context object.

Function: inject.getter

inject.getter(bindingSelector: BindingSelector<unknown>, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject a function for getting the actual bound value.

This is useful when implementing Actions, where the action is instantiated for Sequence constructor, but some of action's dependencies become bound only after other actions have been executed by the sequence.

See also Getter<T>.

Parameters
Name Type Default Value Flags Description
bindingSelector BindingSelector<unknown>

The binding key or filter we want to eventually get value(s) from.

metadata InjectionMetadata optional

Optional metadata to help the injection

Function: inject.setter

inject.setter(bindingKey: BindingAddress, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject a function for setting (binding) the given key to a given value. (Only static/constant values are supported, it's not possible to bind a key to a class or a provider.)

This is useful e.g. when implementing Actions that are contributing new Elements.

See also Setter<T>.

Parameters
Name Type Default Value Flags Description
bindingKey BindingAddress

The key of the value we want to set.

metadata InjectionMetadata optional

Optional metadata to help the injection

Function: inject.tag

inject.tag(bindingTag: BindingTag | RegExp, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject an array of values by a tag pattern string or regexp

Parameters
Name Type Default Value Flags Description
bindingTag BindingTag | RegExp

Tag name, regex or object

metadata InjectionMetadata optional

Optional metadata to help the injection

Function: inject.view

inject.view(bindingFilter: BindingFilter, metadata: InjectionMetadata) : markParameterOrPropertyAsInjected

Inject matching bound values by the filter function

class MyControllerWithView {
  @inject.view(filterByTag('foo'))
  view: ContextView<string[]>;
}

Parameters
Name Type Default Value Flags Description
bindingFilter BindingFilter

A binding filter function

metadata InjectionMetadata optional

Interface: Injection

Descriptor for an injection point

Properties
Name Type Default Value Flags Description
bindingSelector BindingSelector<ValueType> exported

Descriptor for an injection point

member undefined | string exported optional

Descriptor for an injection point

metadata InjectionMetadata exported

Descriptor for an injection point

methodDescriptorOrParameterIndex TypedPropertyDescriptor<ValueType> | number exported optional

Descriptor for an injection point

resolve ResolverFunction exported optional

Descriptor for an injection point

target Object exported

Descriptor for an injection point

Interface: InjectionMetadata

An object to provide metadata for @inject

Properties
Name Type Default Value Flags Description
decorator undefined | string exported optional

Name of the decorator function, such as @inject or @inject.setter. It's usually set by the decorator implementation.

optional undefined | false | true exported optional

Control if the dependency is optional, default to false

Interface: ResolverFunction

A function to provide resolution of injected values

Type alias: Setter(value: T): void

The function injected by @inject.setter(key).

Arguments
Name Type Description
value T

Function: describeInjectedArguments

describeInjectedArguments(target: Object, method: undefined | string) : Readonly<Injection>[]

Return an array of injection objects for parameters

Parameters
Name Type Default Value Flags Description
target Object

The target class for constructor or static methods, or the prototype for instance methods

method undefined | string optional

Method name, undefined for constructor

Function: describeInjectedProperties

describeInjectedProperties(target: Object) : MetadataMap<Readonly<Injection>>

Return a map of injection objects for properties

Parameters
Name Type Default Value Flags Description
target Object

The target class for static properties or prototype for instance properties.

Namespace: ContextTags

const ContextTags.CLASS = "class"

const ContextTags.KEY = "key"

Binding key for the artifact

const ContextTags.NAME = "name"

Name of the artifact

const ContextTags.NAMESPACE = "namespace"

Namespace of the artifact

const ContextTags.PROVIDER = "provider"

const ContextTags.TYPE = "type"

Type of the artifact

Interface: Provider

Providers allow developers to compute injected values dynamically, with any dependencies required by the value getter injected automatically from the Context.

value() : ValueOrPromise<T>

Returns:

The value to inject to dependents. This method can return a promise too, in which case the IoC framework will resolve this promise to obtain the value to inject.

Class: resolutionsession = new ResolutionSession()

Object to keep states for a session to resolve bindings and their dependencies within a context

Properties
Name Type Default Value Flags Description
stack ResolutionElement[] [] exported

A stack of bindings for the current resolution session. It's used to track the path of dependency resolution and detect circular dependencies.

bindingStack() :

currentBinding() :

currentInjection() :

injectionStack() :

getBindingPath() : string

Get the binding path as bindingA --> bindingB --> bindingC.

getInjectionPath() : string

Get the injection path as injectionA --> injectionB --> injectionC.

getResolutionPath() : string

Get the resolution path including bindings and injections, for example: bindingA --> @ClassA[0] --> bindingB --> @ClassB.prototype.prop1 --> bindingC.

popBinding() : Readonly<Binding>

Exit the resolution of a binding

popInjection() : anonymous

Pop the last injection

pushBinding(binding: Readonly<Binding>) : void

Enter the resolution of the given binding. If

Parameters
Name Type Default Value Flags Description
binding Readonly<Binding>

Binding

pushInjection(injection: Readonly<Injection>) : void

Push the injection onto the session

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection>

Injection The current injection

describeInjection(injection: Readonly<Injection>) : undefined | anonymous

Describe the injection for debugging purpose

Parameters
Name Type Default Value Flags Description
injection Readonly<Injection> optional

Injection object

fork(session: ResolutionSession) : ResolutionSession | undefined

Fork the current session so that a new one with the same stack can be used in parallel or future resolutions, such as multiple method arguments, multiple properties, or a getter function

Parameters
Name Type Default Value Flags Description
session ResolutionSession optional

The current session

runWithBinding(action: ResolutionAction, binding: Readonly<Binding>, session: ResolutionSession) : any

Run the given action with the given binding and session

Parameters
Name Type Default Value Flags Description
action ResolutionAction

A function to do some work with the resolution session

binding Readonly<Binding>

The current binding

session ResolutionSession optional

The current resolution session

runWithInjection(action: ResolutionAction, injection: Readonly<Injection>, session: ResolutionSession) : any

Run the given action with the given injection and session

Parameters
Name Type Default Value Flags Description
action ResolutionAction

A function to do some work with the resolution session

injection Readonly<Injection>

Object to keep states for a session to resolve bindings and their dependencies within a context

session ResolutionSession optional

The current resolution session

Interface: BindingElement

Wrapper for bindings tracked by resolution sessions

Properties
Name Type Default Value Flags Description
type exported

Wrapper for bindings tracked by resolution sessions

value Readonly<Binding> exported

Wrapper for bindings tracked by resolution sessions

Interface: InjectionElement

Wrapper for injections tracked by resolution sessions

Properties
Name Type Default Value Flags Description
type exported

Wrapper for injections tracked by resolution sessions

value Readonly<Injection> exported

Wrapper for injections tracked by resolution sessions

Interface: ResolutionOptions

Options for binding/dependency resolution

Properties
Name Type Default Value Flags Description
optional undefined | false | true exported optional

A boolean flag to indicate if the dependency is optional. If it's set to true and the binding is not bound in a context, the resolution will return undefined instead of throwing an error.

session ResolutionSession exported optional

A session to track bindings and injections

Type alias: ResolutionAction(session: ResolutionSession): ValueOrPromise

A function to be executed with the resolution session

Arguments
Name Type Description
session ResolutionSession

Function: asResolutionOptions

asResolutionOptions(optionsOrSession: ResolutionOptionsOrSession) : ResolutionOptions

Normalize ResolutionOptionsOrSession to ResolutionOptions

Parameters
Name Type Default Value Flags Description
optionsOrSession ResolutionOptionsOrSession optional

resolution options or session

Function: instantiateClass

instantiateClass(ctor: Constructor<T>, ctx: Context, session: ResolutionSession, nonInjectedArgs: any[]) : ValueOrPromise<T>

Create an instance of a class which constructor has arguments decorated with @inject.

The function returns a class when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
ctor Constructor<T>

The class constructor to call.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: invokeMethod

invokeMethod(target: Object, method: string, ctx: Context, nonInjectedArgs: any[]) : ValueOrPromise<BoundValue>

Invoke an instance method with dependency injection

Parameters
Name Type Default Value Flags Description
target Object

Target of the method, it will be the class for a static method, and instance or class prototype for a prototype method

method string

Name of the method

ctx Context

Context

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: resolveInjectedArguments

resolveInjectedArguments(target: Object, method: string, ctx: Context, session: ResolutionSession, nonInjectedArgs: any[]) : ValueOrPromise<BoundValue[]>

Given a function with arguments decorated with @inject, return the list of arguments resolved using the values bound in ctx.

The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
target Object

The class for constructor injection or prototype for method injection

method string

The method name. If set to '', the constructor will be used.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

nonInjectedArgs any[] optional

Optional array of args for non-injected parameters

Function: resolveInjectedProperties

resolveInjectedProperties(constructor: Function, ctx: Context, session: ResolutionSession) : ValueOrPromise<MapObject<BoundValue>>

Given a class with properties decorated with @inject, return the map of properties resolved using the values bound in ctx.

The function returns an argument array when all dependencies were resolved synchronously, or a Promise otherwise.

Parameters
Name Type Default Value Flags Description
constructor Function

The class for which properties should be resolved.

ctx Context

The context containing values for @inject resolution

session ResolutionSession optional

Optional session for binding and dependency resolution

Type alias: BoundValue = any

Type alias: MapObject(name: string): T

Arguments
Name Type Description
name string

Function: getDeepProperty

getDeepProperty(value: IN, path: string) : OUT | undefined

Get nested properties of an object by path

Parameters
Name Type Default Value Flags Description
value IN

Value of the source object

path string

Path to the property

Function: isPromiseLike

isPromiseLike(value: T | PromiseLike<T> | undefined) : boolean

Check whether a value is a Promise-like instance. Recognizes both native promises and third-party promise libraries.

Parameters
Name Type Default Value Flags Description
value T | PromiseLike<T> | undefined

The value to check.

Function: resolveList

resolveList(list: T[], resolver: (val: T, index: number, list: T[]) => ValueOrPromise<V>) : ValueOrPromise<V[]>

Resolve entries of an array into a new array with the same indexes. If one or more entries of the source array are resolved to a promise by the resolver function, this method returns a promise which will be resolved to the new array with fully resolved entries.

Parameters
Name Type Default Value Flags Description
list T[]

The original array containing the source entries

resolver anonymous

A function resolves an entry to a value or promise. It will be invoked with the property value, the property index, and the source array.

Function: resolveMap

resolveMap(map: MapObject<T>, resolver: (val: T, key: string, map: MapObject<T>) => ValueOrPromise<V>) : ValueOrPromise<MapObject<V>>

Resolve entries of an object into a new object with the same keys. If one or more entries of the source object are resolved to a promise by the resolver function, this method returns a promise which will be resolved to the new object with fully resolved entries.

Parameters
Name Type Default Value Flags Description
map MapObject<T>

The original object containing the source entries

resolver anonymous

A function resolves an entry to a value or promise. It will be invoked with the property value, the property name, and the source object.

Function: resolveUntil

resolveUntil(source: Iterator<T>, resolver: (sourceVal: T) => ValueOrPromise<V | undefined>, evaluator: (sourceVal: T, targetVal: V | undefined) => boolean) : ValueOrPromise<V | undefined>

Resolve an iterator of source values into a result until the evaluator returns true

Parameters
Name Type Default Value Flags Description
source Iterator<T>

The iterator of source values

resolver anonymous

The resolve function that maps the source value to a result

evaluator anonymous

The evaluate function that decides when to stop

Function: transformValueOrPromise

transformValueOrPromise(valueOrPromise: ValueOrPromise<T>, transformer: (val: T) => ValueOrPromise<V>) : ValueOrPromise<V>

Transform a value or promise with a function that produces a new value or promise

Parameters
Name Type Default Value Flags Description
valueOrPromise ValueOrPromise<T>

The value or promise

transformer anonymous

A function that maps the source value to a value or promise

Function: tryWithFinally

tryWithFinally(action: () => ValueOrPromise<T>, finalAction: () => void) : ValueOrPromise<T>

Try to run an action that returns a promise or a value

Parameters
Name Type Default Value Flags Description
action anonymous

A function that returns a promise or a value

finalAction anonymous

A function to be called once the action is fulfilled or rejected (synchronously or asynchronously)