From eea8bcc8ebd63ec316d39f43d4284f79a9c47b5e Mon Sep 17 00:00:00 2001 From: Janne Savolainen Date: Fri, 8 Apr 2022 15:13:03 +0300 Subject: [PATCH] feat: Expose deregister to instantiate --- .../injectable/ogre-tools-injectable.d.ts | 2 ++ .../createContainer.deregistration.test.js | 27 +++++++++++++++++++ .../createContainer.js | 2 ++ 3 files changed, 31 insertions(+) diff --git a/packages/injectable/ogre-tools-injectable.d.ts b/packages/injectable/ogre-tools-injectable.d.ts index 452ee4ab..d2bed524 100644 --- a/packages/injectable/ogre-tools-injectable.d.ts +++ b/packages/injectable/ogre-tools-injectable.d.ts @@ -28,6 +28,8 @@ export interface DiContainer extends DiContainerForInjection { InstantiationParam >[] ): void; + + deregister(...injectables: Injectable[]): void; preventSideEffects: () => void; } diff --git a/packages/injectable/src/dependency-injection-container/createContainer.deregistration.test.js b/packages/injectable/src/dependency-injection-container/createContainer.deregistration.test.js index 381fe5dd..17c65c60 100644 --- a/packages/injectable/src/dependency-injection-container/createContainer.deregistration.test.js +++ b/packages/injectable/src/dependency-injection-container/createContainer.deregistration.test.js @@ -75,4 +75,31 @@ describe('createContainer.deregistration', () => { const actual = di.inject(someInjectable); expect(actual).toBe('some-instance'); }); + + it('given injectable and injectable which can deregister and first injectable is deregistered, when first injectable is injected, throws', () => { + const di = createContainer(); + + const someInjectable = getInjectable({ + id: 'some-injectable', + instantiate: () => 'some-instance', + }); + + const deregisterInjectable = getInjectable({ + id: 'deregister', + + instantiate: di => injectable => { + di.deregister(injectable); + }, + }); + + di.register(someInjectable, deregisterInjectable); + + const deregister = di.inject(deregisterInjectable); + + deregister(someInjectable); + + expect(() => { + di.inject(someInjectable); + }).toThrow('Tried to inject non-registered injectable "some-injectable".'); + }); }); diff --git a/packages/injectable/src/dependency-injection-container/createContainer.js b/packages/injectable/src/dependency-injection-container/createContainer.js index 83ea7d9d..782ab1f3 100644 --- a/packages/injectable/src/dependency-injection-container/createContainer.js +++ b/packages/injectable/src/dependency-injection-container/createContainer.js @@ -279,6 +279,8 @@ const getInstance = ({ context: newContext, register: di.register, + + deregister: di.deregister, }; const instanceKey = injectable.lifecycle.getInstanceKey(