From 924bef9e29e077fdbb6a4362d29398429de1b24e Mon Sep 17 00:00:00 2001 From: zhangpanweb <37805064+zhangpanweb@users.noreply.github.com> Date: Tue, 12 Dec 2023 21:13:40 +0800 Subject: [PATCH] fix: hooked class will be instantiate multiple times (#119) --- src/injector.ts | 2 +- test/aspect.test.ts | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/src/injector.ts b/src/injector.ts index 595a208..851ac99 100644 --- a/src/injector.ts +++ b/src/injector.ts @@ -354,7 +354,7 @@ export class Injector { let instance: any; const getInstance = () => { if (!instance) { - instance = this.get(creator.useClass); + instance = this.get(token); this.onceInstanceDisposed(instance, () => { if (toDispose) { toDispose.dispose(); diff --git a/test/aspect.test.ts b/test/aspect.test.ts index 133a870..cba336f 100644 --- a/test/aspect.test.ts +++ b/test/aspect.test.ts @@ -124,4 +124,42 @@ describe('aspect', () => { expect(result).toBe(3); }); + + it('aspect针对token注入的内容,不会多次实例化', () => { + const spy = jest.fn(); + + @Injectable() + class B { + async do() { + console.log('do'); + } + } + @Aspect() + @Injectable() + class A { + constructor() { + spy(); + } + + @Around(B, 'do', { await: true }) + async aroundDo() { + console.log('aroundDo'); + } + } + const token = 'token'; + + const injector = new Injector(); + injector.addProviders({ + token, + useClass: A, + }); + injector.addProviders(B); + injector.get(token); + injector.get(B); + expect(spy).toHaveBeenCalledTimes(1); + + const b = injector.get(B); + b.do(); + expect(spy).toHaveBeenCalledTimes(1); + }); });