Skip to content

IDependencyContainer

github-actions[bot] edited this page Dec 3, 2024 · 3 revisions
API / IDependencyContainer interface

Represents a dependency container for configuring and later on resolving dependencies similar to a dependency injection mechanism.

interface IDependencyContainer

Source reference: src/dependencies/IDependencyContainer.ts:75.

Description

There are three levels for configuring dependencies.

Singleton - dependencies are initialized only once and each time they are requested the same instance is returned.

Scoped - dependencies are initialized only one for each scope. Whenever the same dependency is resolved in the same scope, the same instance is returned. When a dependency is requested in different scopes, different instances are returned.

Transient - dependencies are initialized each time they are requested, this is the default for all types allowing for seamless use of the container regardless of whether types are configured or not.

The above is exemplified using the following code snippet.

const dependencyContainer = new DependencyContainer()
  .registerSingletonType(MyFirstClass)
  .registerScopedType(MySecondClass);

const singletonInstance1 = dependencyContainer.resolve(MyFirstClass);
const singletonInstance2 = dependencyContainer.resolve(MyFirstClass);
singletonInstance1 === singletonInstance2; // true

const scope1 = dependencyContainer.createScope();
const scope2 = dependencyContainer.createScope();
const scopedInstance1 = scope1.resolve(MySecondClass);
const scopedInstance2 = scope1.resolve(MySecondClass);
const scopedInstance3 = scope2.resolve(MySecondClass);
scopedInstance1 === scopedInstance2; // true
scopedInstance1 === scopedInstance3; // false

const transient1 = dependencyContainer.resolve(MyThirdClass);
const transient2 = dependencyContainer.resolve(MyThirdClass);
transient1 === transient2; // false

Methods

Implementations

See also

Clone this wiki locally