Container.ts
54 lines
| 2.2 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r0 | import { ActivationContext } from "./ActivationContext"; | ||
| import { ActivationError } from "./ActivationError"; | ||||
|
|
r5 | import { ContainerBuilder } from "./ContainerBuilder"; | ||
| import { RegistrationMap, ServiceContainer, ContainerServices, ServiceLocator, IContainerBuilder, Configurable, ContainerKeys} from "./interfaces"; | ||||
|
|
r0 | import { LifetimeManager } from "./LifetimeManager"; | ||
|
|
r5 | export class Container<S extends Configurable<S>> implements ServiceContainer<S> { | ||
|
|
r1 | private readonly _services: Partial<RegistrationMap<ContainerServices<S>>>; | ||
|
|
r0 | |||
|
|
r1 | private readonly _lifetimeManager: LifetimeManager; | ||
|
|
r0 | |||
|
|
r1 | private _disposed: boolean; | ||
|
|
r0 | |||
|
|
r5 | constructor(services: Partial<RegistrationMap<ContainerServices<S>>>, lifetimeManager: LifetimeManager) { | ||
| this._services = services; | ||||
| this._services.container = { activate: () => this as ContainerServices<S>["container"]}; | ||||
| this._services.childContainer = { activate: () => this.createChildContainer() as ContainerServices<S>["childContainer"] }; | ||||
|
|
r0 | this._disposed = false; | ||
|
|
r5 | this._lifetimeManager = lifetimeManager; | ||
|
|
r0 | } | ||
|
|
r5 | createChildContainer(): IContainerBuilder<S> { | ||
| return new ContainerBuilder(this._services); | ||||
|
|
r0 | } | ||
|
|
r5 | resolve<K extends keyof ContainerServices<S>>(name: K): NonNullable<ContainerServices<S>[K]>; | ||
| resolve<K extends keyof ContainerServices<S>, T>(name: K, def: T): NonNullable<ContainerServices<S>[K]> | T; | ||||
| resolve<K extends keyof ContainerServices<S>, T>(name: K, def?: T) { | ||||
|
|
r1 | // TODO: add logging | ||
| // trace.debug("resolve {0}", name); | ||||
|
|
r0 | const d = this._services[name]; | ||
| if (d === undefined) { | ||||
| if (arguments.length > 1) | ||||
| return def; | ||||
| else | ||||
|
|
r1 | throw new Error(`Service '${String(name)}' isn't found`); | ||
|
|
r0 | } else { | ||
|
|
r5 | const context = new ActivationContext(this._lifetimeManager, this._services, String(name), d); | ||
|
|
r0 | try { | ||
| return d.activate(context); | ||||
| } catch (error) { | ||||
| throw new ActivationError(name.toString(), context.getStack(), error); | ||||
| } | ||||
| } | ||||
| } | ||||
| destroy() { | ||||
| if (this._disposed) | ||||
| return; | ||||
| this._disposed = true; | ||||
| this._lifetimeManager.destroy(); | ||||
| } | ||||
| } | ||||
