Container.ts
64 lines
| 2.2 KiB
| video/mp2t
|
TypeScriptLexer
|
|
r0 | import { ActivationContext } from "./ActivationContext"; | ||
| import { ActivationError } from "./ActivationError"; | ||||
|
|
r5 | import { ContainerBuilder } from "./ContainerBuilder"; | ||
|
|
r13 | import { LifetimeManager } from "./LifetimeManager"; | ||
|
|
r9 | import { DescriptorMap, IContainerBuilder, IDestroyable, ILifetimeManager, ServiceLocator } from "./interfaces"; | ||
|
|
r0 | |||
|
|
r9 | export class Container<S> implements ServiceLocator<S>, IDestroyable { | ||
| private readonly _services: DescriptorMap<S>; | ||||
|
|
r0 | |||
|
|
r13 | private readonly _lifetimeManagers: ILifetimeManager[]; | ||
|
|
r0 | |||
|
|
r1 | private _disposed: boolean; | ||
|
|
r0 | |||
|
|
r9 | private readonly _onDestroyed: () => void; | ||
|
|
r13 | constructor(services: DescriptorMap<S>, lifetimeManagers: ILifetimeManager[], destroyed: () => void) { | ||
| this._services = services; | ||||
|
|
r0 | this._disposed = false; | ||
|
|
r13 | this._lifetimeManagers = lifetimeManagers.concat(new LifetimeManager()); | ||
|
|
r9 | this._onDestroyed = destroyed; | ||
|
|
r0 | } | ||
|
|
r9 | private _assertNotDestroyed() { | ||
| if (this._disposed) | ||||
| throw new Error("The container is destroyed"); | ||||
|
|
r0 | } | ||
|
|
r9 | createChildBuilder(): IContainerBuilder<S, keyof S> { | ||
| this._assertNotDestroyed(); | ||||
| const lifetime = this._lifetimeManager.create<IDestroyable>(); | ||||
| return new ContainerBuilder(this._services, lifetime); | ||||
| } | ||||
| resolve<K extends keyof S>(name: K): NonNullable<S[K]>; | ||||
| resolve<K extends keyof S, T>(name: K, def: T): NonNullable<S[K]> | T; | ||||
| resolve<K extends keyof S, T>(name: K, def?: T) { | ||||
| this._assertNotDestroyed(); | ||||
|
|
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 { | ||
|
|
r13 | const context = new ActivationContext(this._lifetimeManagers, 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(); | ||||
|
|
r9 | (0,this._onDestroyed)(); | ||
|
|
r0 | } | ||
| } | ||||
