Skip to content

Lazy resolution

Max Gherman edited this page Jul 5, 2019 · 3 revisions

Lazy resolution is used for situations where resolution of services has to be differed until results are needed by other services/computations. Specifically, arguments passed to a service are not evaluated before they are passed to a function/constructor, but only when their values are actually used. It is a responsibility of the calling services to trigger evaluation of lazy dependencies when needed. All dependencies configured as lazy are passed as functions. The process of evaluation involves invoking corresponding functions and using their results.

To configure lazy service we mark it as lazy during registration as part of fluent API process. Lazy registration is also available for decorator style API registration.

TypeScript

import { builder as createBuilder,  IContainer} from 'typeioc';

const builder = createBuilder();

interface IFib {
    value: number;
    next: IFib;
}

builder.register('F')
.as((c: IContainer, h, n) => {
    const a = c.resolve<() => IFib>('F', n, h + n);

    return {
        value: h,
        get next() {
            return a();
        }
   };
})
.lazy();

const container = builder.build();
const lazy = container.resolve<() => IFib>('F', 0, 1)();

const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce((acc) => {
    acc.result.push(acc.lazy.value);
    acc.lazy = acc.lazy.next;
    return acc;
}, { lazy, result: [] });

Run example

JavaScript

 import { builder as createBuilder} from 'typeioc';

const builder = createBuilder();

builder.register('F')
.as((c, h, n) => {
    const a = c.resolve('F', n, h + n);

    return {
        value: h,
        get next() {
            return a();
        }
   };
})
.lazy();

const container = builder.build();
const lazy = container.resolve('F', 0, 1)();

const data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].reduce((acc) => {
    acc.result.push(acc.lazy.value);
    acc.lazy = acc.lazy.next;
    return acc;
}, { lazy, result: [] });

Run example