import { TraceSource } from "../log/TraceSource"; import { argumentNotNull, argumentNotEmptyString } from "../safe"; import { Descriptor, ContainerServiceMap, ContainerKeys, ContainerResolve } from "./interfaces"; import { Container } from "./Container"; import { MapOf } from "../interfaces"; const trace = TraceSource.get("@implab/core/di/ActivationContext"); export interface ActivationContextInfo { name: string; service: string; } export class ActivationContext { _cache: MapOf; _services: ContainerServiceMap; _visited: MapOf; _name: string; _service: Descriptor; _container: Container; _parent: ActivationContext | undefined; constructor(container: Container, services: ContainerServiceMap, name: string, service: Descriptor) { this._name = name; this._service = service; this._visited = {}; this._cache = {}; this._services = services; this._container = container; } getName() { return this._name; } getContainer() { return this._container; } resolve>(name: K, def?: ContainerResolve) { const d = this._services[name]; if (d !== undefined) { return this.activate(d, name.toString()); } else { if (def !== undefined && def !== null) return def; else throw new Error(`Service ${name} not found`); } } /** * registers services local to the the activation context * * @name{string} the name of the service * @service{string} the service descriptor to register */ register(name: K, service: Descriptor) { argumentNotEmptyString(name, "name"); this._services[name] = service as any; } has(id: string) { return id in this._cache; } get(id: string) { return this._cache[id]; } store(id: string, value: any) { return (this._cache[id] = value); } activate(d: Descriptor, name: string) { if (trace.isLogEnabled()) trace.log(`enter ${name} ${d}`); const ctx = this.enter(d, name); const v = d.activate(ctx); if (trace.isLogEnabled()) trace.log(`leave ${name}`); return v; } visit(id: string) { const count = this._visited[id] || 0; this._visited[id] = count + 1; return count; } getStack(): ActivationContextInfo[] { const stack = [{ name: this._name, service: this._service.toString() }]; return this._parent ? stack.concat(this._parent.getStack()) : stack; } private enter(service: Descriptor, name: string): this { const clone = Object.create(this); clone._name = name; clone._services = Object.create(this._services); clone._parent = this; clone._service = service; return clone; } }