Page MenuHomeWildfire Games

Dependency Injection

Authored By
lyv
Jun 3 2022, 2:31 PM
Size
1 KB
Referenced Files
None
Subscribers
None

Dependency Injection

const Injector = new class
{
constructor()
{
this.services = new WeakMap();
this.objectCache = new WeakMap();
}
registerService(___)
{
let TService = arguments[0];
let TServiceArgs = [];
if (arguments.length > 1)
{
for (let i = 1; i < arguments.length; ++i)
{
TServiceArgs.push(arguments[i]);
}
}
let args = [null].concat(TServiceArgs);
let instance = new (Function.prototype.bind.apply(TService, args));
this.services.set(TService, instance);
}
getService(TService)
{
if (this.services.has(TService))
{
return this.services.get(TService);
}
else
{
error("No service of " + TService.name + " is registered");
}
}
get(___)
{
let TObject = arguments[0];
let TObjectArgs = [];
if (arguments.length > 1)
{
for (let i = 1; i < arguments.length; ++i)
{
TObjectArgs.push(arguments[i]);
}
}
if (!TObject.deps)
{
error("The class " + TObject.name + " does not define any dependencies");
}
let services = [];
if (!this.objectCache.has(TObject))
{
for (let dep of TObject.deps)
{
if (this.services.has(dep))
{
services.push(this.services.get(dep));
}
else
{
error("Can't resolve dependency " + dep.name + " for " + TObject.name);
}
}
this.objectCache.set(TObject, services);
}
else
{
services = this.objectCache.get(TObject);
}
let args = [null].concat(services).concat(TObjectArgs);
let instance = new (Function.prototype.bind.apply(TObject, args));
return instance;
}
};

File Metadata

Mime Type
text/plain; charset=utf-8
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
1952669
Default Alt Text
Dependency Injection (1 KB)

Event Timeline