ts-ioc-container
Version:
Typescript IoC container
73 lines (72 loc) • 2.1 kB
JavaScript
import { isDependencyKey } from './container/IContainer';
import { isDepKey } from './DepKey';
export class InjectionResolver {
resolveByOptions;
isLazy = false;
getArgs = () => [];
constructor(resolveByOptions) {
this.resolveByOptions = resolveByOptions;
}
args(...deps) {
this.getArgs = () => deps;
return this;
}
argsFn(fn) {
this.getArgs = fn;
return this;
}
lazy() {
this.isLazy = true;
return this;
}
resolve(s) {
return this.resolveByOptions(s, {
lazy: this.isLazy,
args: this.getArgs(s),
});
}
}
export class InstancesResolver {
predicate;
isCascade = true;
constructor(predicate) {
this.predicate = predicate;
}
cascade(isTrue) {
this.isCascade = isTrue;
return this;
}
resolve(c) {
const result = new Set(c.getInstances().filter(this.predicate));
if (this.isCascade) {
for (const s of c.getScopes()) {
for (const instance of s.getInstances().filter(this.predicate)) {
result.add(instance);
}
}
}
return [...result];
}
}
export const by = {
many: (target) => {
const alias = isDependencyKey(target) ? target : target.key;
return new InjectionResolver((s, options) => s.resolveMany(alias, options));
},
one: (target) => {
const key = isDepKey(target) ? target.key : target;
return new InjectionResolver((s, options) => s.resolveOne(key, options));
},
/**
* Use it only for optimization. Otherwise, recommended to use `by.one`
*/
aliasOne: (target) => {
const alias = isDepKey(target) ? target.key : target;
return new InjectionResolver((s, options) => s.resolveOneByAlias(alias, options));
},
instances: (predicate = () => true) => new InstancesResolver(predicate),
scope: {
current: (container) => container,
create: (options) => (l) => l.createScope(options),
},
};