Skip to main content

Container

Container is a Brandi class whose instances store information about dependencies, resolve dependencies, and inject dependencies into targets.

Container Methods#

bind(token)#

Binds the token to an implementation.

Arguments#

  1. token: Token โ€” a token to be bound.

Returns#

Binding Type syntax:


use(...tokens).from(module)#

Uses bindings from a dependency module.

Arguments#

use(...tokens)#
  1. ...tokens: Token[] โ€” tokens to be used from a dependency module.
use(...tokens).from(module)#
  1. module: DependencyModule โ€” a dependency module.

when(condition)#

Creates a conditional binding.

Arguments#

  1. condition: Tag | UnknownCreator โ€” a condition.

Returns#

bind or use syntax:


extend(container)#

Sets the parent container. For more information, see Hierarchical Containers section.

Arguments#

  1. container: Container | null โ€” a Container or null that will be set as the parent container.

Returns#

this โ€” the container.


get(token)#

Gets a dependency bound to the token.

Arguments#

  1. token: TokenValue โ€” token for which a dependence will be got.

Returns#

TokenType<TokenValue> โ€” a dependency bound to the token.


clone()#

Returns an unlinked clone of the container.

Returns#

Container โ€” new container.

Example#

import { Container } from 'brandi';
const originalContainer = new Container();
const containerClone = originalContainer.clone();
expect(containerClone).toBeInstanceOf(Container);
expect(containerClone).not.toBe(originalContainer);

capture()#

Captures (snapshots) the current container state.

note

The capture() method works only in development mode (process.env.NODE_ENV !== 'production').

Container.capture is undefined in production mode.

restore()#

Restores the captured container state.

note

The restore() method works only in development mode (process.env.NODE_ENV !== 'production').

Container.restore is undefined in production mode.

Example#

import { Container, token } from 'brandi';
const TOKENS = {
apiKey: token<string>('API Key'),
};
const container = new Container();
container.bind(TOKENS.apiKey).toConstant('#key9428');
container.capture();
container.bind(TOKENS.apiKey).toConstant('#testKey');
const testKey = container.get(TOKENS.apiKey);
container.restore();
const originalKey = container.get(TOKENS.apiKey);
expect(testKey).toBe('#testKey');
expect(originalKey).toBe('#key9428');

createContainer()#

createContainer() โ€” is alias for new Container().