##// END OF EJS Templates
WIP lifetime, service descriptors
WIP lifetime, service descriptors

File last commit:

r14:3f8a82c8ce73 default
r14:3f8a82c8ce73 default
Show More
ContainerBuilder.ts
65 lines | 2.1 KiB | video/mp2t | TypeScriptLexer
/ src / main / ts / ContainerBuilder.ts
import { Container } from "./Container";
import { DescriptorBuilder } from "./DescriptorBuilder";
import { containerSelfDescriptor } from "./DescriptorImpl";
import { Descriptor, IContainerBuilder, IDescriptorBuilder, DescriptorMap, ServiceLocator, ILifetime, IDestroyable, ContainerServices, ContainerServicesConstraint } from "./interfaces";
import { emptyLifetime, LifetimeManager } from "./LifetimeManager";
import { isDestroyable, prototype } from "./traits";
/**
* Container builder used to prepare service descriptors and create a IoC container
*/
export class ContainerBuilder<S, U extends keyof S> implements
IContainerBuilder<S, U> {
private _pending = 1;
private readonly _services: DescriptorMap<ContainerServices<S>>;
private readonly _lifetimeManager = new LifetimeManager();
private readonly _lifetime: ILifetime<IDestroyable>;
constructor(parentServices: DescriptorMap<S> | null = null, lifetime?: ILifetime<IDestroyable>) {
this._services = { ...parentServices }; // create a copy
this._lifetime = lifetime ?? emptyLifetime();
}
createServiceBuilder<K extends U>(name: K):
IDescriptorBuilder<S, S[K], Record<never, never>, U> {
return new DescriptorBuilder(this._lifetimeManager, this._register(name), this._fail);
}
build(): ServiceLocator<S> {
this._assertBuilding();
if (!this._complete())
throw new Error("The configuration didn't complete.");
const {remove, store} = this._lifetime(null);
const container = new Container(this._services, this._lifetimeManager, remove);
store(container);
return container;
}
private readonly _register = <K extends U>(name: K) =>
(descriptor: Descriptor<S, S[K]>) => {
this._complete();
this._services[name] = descriptor;
};
private readonly _fail = (ex: unknown) => {
throw ex;
};
private _assertBuilding() {
if (!this._pending)
throw new Error("The descriptor builder is finalized");
}
private _complete() {
return !(--this._pending);
}
}