2021-08-17 19:25:27 +00:00
|
|
|
/*
|
2021-08-17 19:38:20 +00:00
|
|
|
* Modified version of code by Magnus Tovslid:
|
2021-08-17 19:25:27 +00:00
|
|
|
* https://medium.com/@magnusjt/ioc-container-in-nodejs-e7aea8a89600
|
|
|
|
*/
|
|
|
|
class Container
|
|
|
|
{
|
|
|
|
constructor()
|
|
|
|
{
|
|
|
|
this.services = {};
|
|
|
|
}
|
|
|
|
|
2021-08-17 19:38:20 +00:00
|
|
|
|
|
|
|
// 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)
|
2021-08-17 19:25:27 +00:00
|
|
|
{
|
|
|
|
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;
|