UNPKG

async-injection

Version:

A robust lightweight dependency injection library for TypeScript.

52 lines 2.41 kB
import { InvokeReleaseMethod } from './utils.js'; /** * Internally all InjectableIds are mapped to an abstract Provider<T>. * A Provider may choose to return a singleton or a new value each time it is queried. */ export class Provider { constructor() { } /** * Base method to initialize the state of this Provider *if* (and only if) it has been configured as a Singleton. * If this Provider has not been configured as a singleton, this method is essentially a noop that returns undefined. * * @param asyncOnly This default implementation ignores this parameter. * @returns A completion Promise if initialization requires asynchronicity, otherwise the return value is undefined. */ resolveIfSingleton(asyncOnly) { if (this.singleton === null) { const s = this.provideAsState(); if (s.pending) return s.promise; else if (s.rejected) return Promise.reject(s.rejected); } return undefined; } /** * If (and only if) this Provider has been configured as a Singleton, and if it has been (or is being resolved), find and invoke the @Release decorated method (if there is one). * NOTE that if the singleton is actively being resolved when this method is called, this method waits for the resolution to complete and then invokes the @Release decorated method; But in any case this is a synchronous method and returns immediately to it's caller. * Also note that invoking this method does not release or invalidate the Provider; * Rather, it resets a Singleton Provider to a fresh (unresolved/unqueried) state (aka sets this.singleton to null). * It is assumed that the Singleton itself will no longer be used after this method returns. */ releaseIfSingleton() { if (this.singleton) { const s = this.provideAsState(); if (s.pending) { s.promise.then((v) => { this.singleton = null; InvokeReleaseMethod(v); }).catch(() => { this.singleton = null; }); } else { this.singleton = null; if ((!s.rejected) && s.fulfilled) InvokeReleaseMethod(s.fulfilled); } } } } //# sourceMappingURL=provider.js.map