Skip to main content

@microsoft/fast-foundation > lazy

lazy variable

A decorator that lazily injects a dependency depending on whether the Key is present at the time of function call.

Signature:
lazy: (key: any) => any

Example 1

You need to make your argument a function that returns the type, for example

class Foo {
constructor( @lazy('random') public random: () => number )
}
const foo = container.get(Foo); // instanceof Foo
foo.random(); // throws

would throw an exception because you haven't registered 'random' before calling the method.

Example 2

This, would give you a new 'Math.random()' number each time.

class Foo {
constructor( @lazy('random') public random: () => random )
}
container.register(Registration.callback('random', Math.random ));
container.get(Foo).random(); // some random number
container.get(Foo).random(); // another random number

@lazy does not manage the lifecycle of the underlying key. If you want a singleton, you have to register as a singleton, transient would also behave as you would expect, providing you a new instance each time.