/* * Modified version of code by Magnus Tovslid: * https://medium.com/@magnusjt/ioc-container-in-nodejs-e7aea8a89600 */ class Container { constructor() { this.services = {}; } // Assumes the class has a static method called create which accepts // a Container style object registerType(name, type) { this.registerFactory(name, c => type.create(c)); } registerInstance(name, instance) { this.registerFactory(name, () => instance); } registerFactory(name, factory) { Object.defineProperty(this, name, { get: () => { if(!this.services.hasOwnProperty(name)) this.services[name] = factory(this); return this.services[name]; }, configurable: true, enumerable: true }); return this; } } module.exports = Container;