ts-lazy-container
v2.0.0
Published
Tool for lazy dependency injection
Maintainers
Readme
ts-lazy-container
This tool manages the creation and distribution of application-wide instances. These are created as singletons or unique variants as needed from provided instructions. In addition, scopes can be used to refine the distribution.
Features
- global dependency injection
- lazy instance injection (create instances on demand)
- class based provisioning/registration
- injection key for type/interface based provisioning/registration
- singleton or unique instance injection
- refined distribution by isolated and inherited scopes (custom, flexible, fine-grained, encapsulated instance injection)
- auto dependency resolution (use provided/registered instructions to resolve object based class constructor parameters)
- lifecycle management (created singletons are disposed with the container)
Installation
npm i ts-lazy-containerUsage
LazyContainer is lazy by design (as the name suggests). Instances will be created on demand during injection. For this to work, types, interfaces or classes must be registered to the container via creation instructions.
Injection Modes
singleton: created instance will be cached and reused on further injections. Dependencies (e.g. constructor parameters) are resolved in 'singleton' mode, toounique: creates a unique instance on each injection. Dependencies (e.g. constructor parameters) are resolved in 'singleton' mode and are therefore NOT uniquedeep-unique: creates a unique instance on each injection. Dependencies (e.g. constructor parameters) are resolved in 'deep-unique' mode and are therefore also unique
Register creation instructions
Identifier =
ClassorInjectionKey
Use provide() to register creation instructions. It covers three forms, chosen automatically from the arguments:
- construction: pass a
Classtogether with its constructor parameters. Simple parameters (primitives, arrays, functions) are passed directly. Object-based parameters do not require concrete instances but must be configured viaidentifiers(aClassorInjectionKey- NOT an instance). The container resolves theseidentifiersautomatically oninject()(lazy), so they must be registered as well. - creation callback: pass a single function
(mode) => instancethat creates the instance (must match the identifier type). Use this to register any Type or Interface via anInjectionKey, or to give aClasscustom creation logic. - delegation: pass a single
identifierthat resolves to an assignable type (inheritance/duck-typing; e.g. resolve anInjectionKeyvia aClass).
Note: a single function argument is always treated as a creation callback, and a single
identifierargument for aClassis always treated as that class' sole constructor parameter.
Identifierscan only be registered once. Duplicate registration will result in an error. If multiple instances of a type are needed, differentInjectionKeysof the same type must be created.
Resolving
inject(identifier, mode?): resolve an instance; throws if no instruction is registered.tryInject(identifier, mode?): likeinject(), but returnsundefinedinstead of throwing.has(identifier): check whether an instruction is registered (including inherited scopes).
container.provide(A);
container.has(A); // true
container.inject(A); // A instance
container.tryInject(B); // undefined (not registered)Overriding
provide() throws on duplicates. Use override() to replace an existing instruction (and drop/dispose its cached singleton) - handy for mocking in tests.
container.provide(Logger, () => new RealLogger());
container.override(Logger, () => new FakeLogger());Disposal
The container is disposable. dispose() (or using via Symbol.dispose) tears it down; removeSingleton()/clearSingletons() evict cached singletons. In every case, evicted/torn-down singletons that expose dispose() or [Symbol.dispose]() are disposed automatically. Only cached singletons created by the container are disposed (not unique/deep-unique instances).
using container = LazyContainer.Create();
container.provide(Connection); // Connection#dispose() runs when the block endsScoping
Scopes allow you to create tree structures within containers. This makes it possible to inject unique instances for specific use cases. These scopes can be created isolated or inherited. A scope is also just a container, so a scope can be created within a scope (and so on...).
- inherited: An inherited scope can resolve instances from its parent. So when the scope tries to inject/resolve an instance (and its dependencies), it first looks for a provided instruction in the scope itself. If none is found, it tries to load it from the parent.
- isolated: An isolated scope cannot access its parent. Therefore, it cannot access the parent's registered instructions and all required instructions must be provided in the scope itself
Application Examples
Types and classes for all example variants
type TypedA = {
text: string;
flag: boolean;
callback: () => void;
};
class A implements TypedA {
constructor(
public text: string,
public flag: boolean,
public callback: () => void
) {}
}
class DependsOnA {
constructor(public a: TypedA, public list: number[]) {}
}Variant 1
Register a class that depends on another (construction form of provide)
import { LazyContainer } from 'ts-lazy-container';
const container = LazyContainer.Create();
container.provide(A, 'hello world', true, () => {});
container.provide(DependsOnA, A, [1, 2, 3, 42]);
// ...
const a = container.inject(A);
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }Variant 2
Mixed usage of the creation-callback and construction forms of provide
import { LazyContainer } from 'ts-lazy-container';
const container = LazyContainer.Create();
container.provide(A, () => new A('hello world', true, () => {}));
container.provide(DependsOnA, A, [1, 2, 3, 42]);
// ...
const a = container.inject(A);
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }Variant 3
Use InjectionKeys to register/inject types or interfaces
import { injectionKey, LazyContainer } from 'ts-lazy-container';
const aInjectionKey = injectionKey<TypedA>();
const container = LazyContainer.Create();
container.provide(
aInjectionKey,
() => new A('hello world', true, () => {})
);
container.provide(DependsOnA, aInjectionKey, [1, 2, 3, 42]);
// ...
const a = container.inject(aInjectionKey); // a: TypedA
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }Variant 4
Use InjectionKeys to register/inject types or interfaces using anonymous objects
import { injectionKey, LazyContainer } from 'ts-lazy-container';
const aInjectionKey = injectionKey<TypedA>();
const container = LazyContainer.Create();
container.provide(aInjectionKey, () => ({
text: 'hello world',
flag: true,
callback: () => {}
}));
container.provide(DependsOnA, aInjectionKey, [1, 2, 3, 42]);
// ...
const a = container.inject(aInjectionKey); // a: TypedA
// => { text: 'hello world'; flag: true; callback: () => {} }
const doa = container.inject(DependsOnA);
// => { a: { text: 'hello world'; flag: true; callback: () => {} }; list: [1, 2, 3, 42] }Variant 5
Mix it all up!
- use a
classas creation instruction for anInjectionsKey - use different
InjectionKeysto register multiple creation instructions of the same type/interface/class
import { injectionKey, LazyContainer } from 'ts-lazy-container';
const doa1InjectionKey = injectionKey<DependsOnA>();
const doa2InjectionKey = injectionKey<DependsOnA>();
const container = LazyContainer.Create();
container.provide(A, 'hello world', true, () => {});
container.provide(DependsOnA, A, [1, 2, 3, 42]);
container.provide(doa1InjectionKey, DependsOnA);
container.provide(
doa2InjectionKey,
() => new DependsOnA(container.inject(A), [5, 6, 7])
);
// ...
const doa1 = container.inject(doa1InjectionKey);
// doa1.list => [1, 2, 3, 42]
const doa2 = container.inject(doa2InjectionKey);
// doa2.list => [5, 6, 7]Variant 6
Inject unique instances - use the correct mode
import { LazyContainer } from 'ts-lazy-container';
const container = LazyContainer.Create();
container.provide(A, 'hello world', true, () => {});
container.provide(DependsOnA, A, [1, 2, 3, 42]);
// ...
const doa1 = container.inject(DependsOnA); // defaults to 'singleton'
const doa2 = container.inject(DependsOnA, 'singleton');
const doa3 = container.inject(DependsOnA, 'unique');
const doa4 = container.inject(DependsOnA, 'deep-unique');
// doa1 === doa2 => true
// doa1 === doa3 => false
// doa1 === doa4 => false
// doa1.a === doa2.a => true
// doa1.a === doa3.a => true
// doa1.a === doa4.a => falseVariant 7
Using scopes for unique or use case related instances.
import { LazyContainer } from 'ts-lazy-container';
class User {
constructor(public name: string, public doa: DependsOnA) {}
}
const container = LazyContainer.Create();
container.provide(A, 'hello world', true, () => {});
container.provide(DependsOnA, A, [1, 2, 3, 42]);
container.provide(User, 'Jack', DependsOnA);
const scientistScope = container.scope('scientist').inherited; // can resolve any instance from parent scope
scientistScope.provide(User, 'Daniel', DependsOnA);
const alienScope = container.scope('alien').isolated; // NO access to parent; need to register dependencies again
alienScope.provide(A, 'hello Chulak', false, () => {});
alienScope.provide(DependsOnA, A, []);
alienScope.provide(User, "Teal'c", DependsOnA);
// ...
const jack = container.inject(User);
const daniel = scientistScope.inject(User);
const tealc = alienScope.inject(User);
// jack === daniel => false
// jack === tealc => false
// jack.name => Jack
// daniel.name => Daniel
// tealc.name => Teal'c
// jack.doa === daniel.doa => true
// jack.doa === tealc.doa => false
// jack.doa.a.text => hello world
// daniel.doa.a.text => hello world
// tealc.doa.a.text => hello Chulak...
