Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 32 additions & 3 deletions src/container/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export class Container {
public readonly id: ContainerIdentifier;

private metadataMap: Map<ServiceIdentifier, Metadata> = new Map();
private bindingMap: Map<ServiceIdentifier, unknown> = new Map();
private resolving = new Set<ServiceIdentifier>();
private resolvingPath: ServiceIdentifier[] = [];

Expand All @@ -30,11 +31,11 @@ export class Container {
return container;
}

public set<T>(metadata: Metadata<T>) {
public register<T>(metadata: Metadata<T>) {
if (metadata.scope === 'singleton' && !this.isDefault()) {
ContainerRegistry.defaultContainer.set(metadata);
ContainerRegistry.defaultContainer.register(metadata);
this.metadataMap.delete(metadata.id);
return;
return this;
}

const newMetadata: Metadata<T> = {
Expand All @@ -48,23 +49,45 @@ export class Container {
} else {
this.metadataMap.set(newMetadata.id, newMetadata);
}

return this;
}

public has(id: ServiceIdentifier): boolean {
return this.metadataMap.has(id);
}

public set<T>(id: ServiceIdentifier<T>, value: T) {
this.bindingMap.set(id, value);
return this;
}

public remove(id: ServiceIdentifier) {
this.bindingMap.delete(id);
this.metadataMap.delete(id);
return this;
}

public reset(strategy: 'value' | 'service' = 'value') {
if (strategy === 'value') {
this.metadataMap.forEach((metadata) => {
metadata.value = EMPTY_VALUE;
});

return this;
} else {
this.bindingMap.clear();
this.metadataMap.clear();

return this;
}
}

public get<T>(id: ServiceIdentifier<T>): T {
if (this.bindingMap.has(id)) {
return this.bindingMap.get(id) as T;
}

let metadata = this.metadataMap.get(id);

if (!metadata && !this.isDefault()) {
Expand Down Expand Up @@ -131,4 +154,10 @@ export class Container {
private isDefault() {
return this === ContainerRegistry.defaultContainer;
}

public static reset(containerId: ContainerIdentifier, options?: { strategy?: 'value' | 'service' }) {
const container = ContainerRegistry.getContainer(containerId);

container?.reset(options?.strategy);
}
}
2 changes: 1 addition & 1 deletion src/decorators/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export function Service<T>(idOrOptions?: ServiceIdentifier | ServiceOption) {

const injections = (context.metadata[INJECTION_KEY] ?? []) as InjectionMetadata[];

ContainerRegistry.defaultContainer.set({
ContainerRegistry.defaultContainer.register({
id: options?.id ?? target,
Class: target,
name: context.name,
Expand Down
Loading
Loading