Skip to content

Commit

Permalink
fix: allow nullable service registrations
Browse files Browse the repository at this point in the history
  • Loading branch information
wessberg committed Oct 18, 2024
1 parent aa68fad commit 0383035
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
5 changes: 2 additions & 3 deletions src/di-container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,13 +92,12 @@ export class DIContainer implements IDIContainer {
if (options == null) {
throw new ReferenceError(`1 argument required, but only 0 present. ${DI_COMPILER_ERROR_HINT}`);
}
const instance = this.#constructInstance<T>(options);

if (instance == null) {
if (!this.has(options)) {
throw new InstantiationError(`The service wasn't found in the registry.`, {identifier: options.identifier});
}

return instance;
return this.#constructInstance<T>(options)!;
}

/**
Expand Down
13 changes: 13 additions & 0 deletions test/di-container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,16 @@ test(`Can construct services with class constructors. #2`, () => {
assert.deepEqual(cInstance.serviceB, bInstance);
assert.deepEqual(bInstance.serviceA, aInstance);
});

test(`Services that allow for nullable values can be constructed without exceptions. #1`, () => {
interface IServiceA {
foo: string;
}

type NullableServiceA = IServiceA | undefined;

const container = new DIContainer();

container.registerSingleton<NullableServiceA>(() => undefined, {identifier: "NullableServiceA"});
assert.doesNotThrow(() => container.get<NullableServiceA>({identifier: "NullableServiceA"}));
});

0 comments on commit 0383035

Please sign in to comment.