Skip to content

Commit

Permalink
fix: hooked class will be instantiate multiple times (#119)
Browse files Browse the repository at this point in the history
  • Loading branch information
zhangpanweb authored Dec 12, 2023
1 parent f586cd5 commit 924bef9
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/injector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
38 changes: 38 additions & 0 deletions test/aspect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});
});

0 comments on commit 924bef9

Please sign in to comment.