@mooncake/container
Version:
DI(dependency injection) container for JavaScript and TypeScript.
94 lines • 2.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const decorators_1 = require("./decorators");
const types_1 = require("./types");
class Registion {
constructor(singleton, scope) {
this.singleton = singleton;
this.scope = scope;
}
/**
* get instance of registion
*
* @param {ContainerResolver} container
* @returns {T}
* @memberof Registion
*/
getInstance(container, scope) {
if (this.instance) {
return this.instance;
}
const ins = this.createInstance(container);
if (this.singleton) {
this.instance = ins;
}
return ins;
}
}
exports.Registion = Registion;
class ValueRegistion extends Registion {
constructor(ins, scope) {
super(true, scope);
this.instance = ins;
}
createInstance(container) {
throw new Error('should not access here');
}
}
exports.ValueRegistion = ValueRegistion;
class ClassRegistion extends Registion {
constructor(clazz, singleton, scope) {
super(singleton, scope);
this.clazz = clazz;
}
createInstance(container) {
let params = [];
const injects = decorators_1.getInjectMetas(this.clazz) || [];
for (let m of injects) {
const index = m.index;
let value;
if (m.resolver) {
value = m.resolver(container, m.scope || this.scope);
}
else if (m.id) {
value = container.get(m.id, m.scope || this.scope);
}
else {
const type = Reflect.getMetadata("design:paramtypes", this.clazz)[index];
value = container.get(type, m.scope || this.scope);
}
if (m.required && [null, void 0].indexOf(value) > -1) {
throw new types_1.InjectError(`can not resolve constructor param[${m.index}]`);
}
params[index] = value;
}
const ins = Reflect.construct(this.clazz, params);
container.fill(ins, this.scope);
return ins;
}
}
exports.ClassRegistion = ClassRegistion;
class FactoryRegistion extends Registion {
constructor(factory, singleton, scope) {
super(singleton, scope);
this.factory = factory;
}
createInstance(container) {
return this.factory.create();
}
}
exports.FactoryRegistion = FactoryRegistion;
class AliasRegistion extends Registion {
constructor(srcId, scope) {
super(false, scope);
this.srcId = srcId;
}
getInstance(container, scope) {
return container.get(this.srcId, scope);
}
createInstance(container) {
throw new Error('should not access here');
}
}
exports.AliasRegistion = AliasRegistion;
//# sourceMappingURL=registion.js.map