Skip to content

Commit 93a8b8e

Browse files
committed
fix: allow nullable service registrations of sub-dependencies
1 parent 64182e3 commit 93a8b8e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/di-container.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -213,7 +213,7 @@ export class DIContainer implements IDIContainer {
213213
parentChain: nextParentChain
214214
});
215215

216-
if (constructedInstance == null) {
216+
if (constructedInstance == null && !this.has({identifier: dep})) {
217217
throw new InstantiationError(`Dependency '${dep}' was not found in the service registry.`, {identifier: me.identifier, parentChain: nextParentChain});
218218
}
219219

test/di-container.test.ts

+23
Original file line numberDiff line numberDiff line change
@@ -187,3 +187,26 @@ test(`Services that allow for nullable values can be constructed without excepti
187187
container.registerSingleton<NullableServiceA>(() => undefined, {identifier: "NullableServiceA"});
188188
assert.doesNotThrow(() => container.get<NullableServiceA>({identifier: "NullableServiceA"}));
189189
});
190+
191+
test(`Services that allow for nullable values can be constructed without exceptions. #2`, () => {
192+
interface IServiceA {
193+
foo: string;
194+
}
195+
196+
type NullableServiceA = IServiceA | undefined;
197+
198+
class ServiceB {
199+
static get [CONSTRUCTOR_ARGUMENTS_SYMBOL]() {
200+
return ["NullableServiceA"];
201+
}
202+
203+
constructor(public serviceA: NullableServiceA) {}
204+
}
205+
206+
const container = new DIContainer();
207+
208+
container.registerSingleton<NullableServiceA>(() => undefined, {identifier: "NullableServiceA"});
209+
container.registerSingleton<ServiceB>(undefined, {identifier: "ServiceB", implementation: ServiceB});
210+
211+
assert.doesNotThrow(() => container.get<ServiceB>({identifier: "ServiceB"}));
212+
});

0 commit comments

Comments
 (0)