UNPKG

@lillallol/dic

Version:

My own dependency injection container.

63 lines (62 loc) 2.76 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Dic = void 0; const getRegistrationStrictOf_1 = require("./getRegistrationStrictOf"); const throwIfAbstractionHasNoName_1 = require("./throwIfAbstractionHasNoName"); const throwIfAlreadyRegistered_1 = require("./throwIfAlreadyRegistered"); const throwIfNotAppropriateFactory_1 = require("./throwIfNotAppropriateFactory"); const validateNumberOfDependencies_1 = require("./validateNumberOfDependencies"); const Dic = class Dic { constructor() { this.registry = new Map(); this.memoizationTable = new Map(); } clearMemoizationTable() { this.memoizationTable.forEach((_v, k) => { const registration = getRegistrationStrictOf_1.getRegistrationStrictOf(this.registry, k); this.memoizationTable.delete(registration.abstraction); }); } register(arg0, arg1) { const { abstraction, factory, dependencies, lifeCycle } = arg0; if (arg1 === undefined) arg1 = {}; const { intercept } = arg1; throwIfAbstractionHasNoName_1.throwIfAbstractionHasNoName(abstraction); throwIfNotAppropriateFactory_1.throwIfFactoryHasNoName(factory); throwIfAlreadyRegistered_1.throwIfAlreadyRegistered(abstraction, this.registry); validateNumberOfDependencies_1.validateNumberOfDependencies(dependencies, factory); this.registry.set(abstraction, { abstraction: abstraction, factory: factory, dependencies: dependencies, lifeCycle: lifeCycle, intercept: intercept ?? [], }); } unregister(parameters) { const { abstraction } = parameters; return this.registry.delete(abstraction); } get(parameters) { const { abstraction, inject } = parameters; const registration = getRegistrationStrictOf_1.getRegistrationStrictOf(this.registry, abstraction); const { dependencies, lifeCycle } = registration; if (this.memoizationTable.has(abstraction)) { return this.memoizationTable.get(abstraction); } const { factory, intercept } = registration; let valueToReturn = factory(...dependencies.map((dependency) => { if (inject !== undefined && inject.has(dependency)) { return inject.get(dependency); } return this.get({ abstraction: dependency, inject }); })); valueToReturn = intercept.reduceRight((a, c) => c({ concretion: a, dic: this }), valueToReturn); if (lifeCycle === "singleton") { this.memoizationTable.set(abstraction, valueToReturn); } return valueToReturn; } }; exports.Dic = Dic;