UNPKG

plain-ioc

Version:

Plain inversion of control container

60 lines (59 loc) 1.95 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const errors_1 = require("./errors"); class Container { constructor() { this.dependencies = new Map(); this.initInstances = new Map(); } bind(key, factory) { if (this.dependencies.has(key)) { throw new errors_1.FactoryAlreadyBoundError(`Factory for ${this.keyToString(key)} already bound`); } this.dependencies.set(key, { factory }); } unbind(key) { if (!this.dependencies.has(key)) { throw new errors_1.FactoryNotBoundError(`Factory not bound with ${this.keyToString(key)}`); } this.dependencies.delete(key); this.initInstances.delete(key); } bindSingleton(key, factory) { if (this.dependencies.has(key)) { throw new errors_1.FactoryAlreadyBoundError(`Factory for ${this.keyToString(key)} already bound`); } this.dependencies.set(key, { factory, singleton: true }); } isBound(key) { return this.dependencies.has(key); } resolve(key) { if (!this.dependencies.has(key)) { throw new errors_1.FactoryNotBoundError(`Factory not bound with ${this.keyToString(key)}`); } const dependency = this.dependencies.get(key); if (dependency.singleton && this.initInstances.has(key)) { return this.initInstances.get(key); } else if (dependency.singleton) { const instance = dependency.factory(this); this.initInstances.set(key, instance); return instance; } return dependency.factory(this); } keyToString(key) { const type = typeof key; if (typeof key === 'function') { key = key.name || ''; } return String(`'${String(key)}' (${type})`); } } exports.Container = Container;