我正在尝试为tsyringe创建一个自定义装饰器以通过属性注入。
我的代码:
import '@abraham/reflection';
import {container} from 'tsyringe';
/**
* Inject class through property
*
* @param targetClass
* @returns PropertyDecorator
*/
export const inject = (targetClass: new (...args: any[]) => any): PropertyDecorator => {
if (!targetClass || targetClass === undefined) {
throw new Error(`${targetClass} class is undefined`);
}
return (target: any, propertyKey: string | symbol): PropertyDecorator => {
return Object.defineProperty(target, propertyKey, {
get: () => container.resolve((targetClass))
});
};
};
服务
import { injectable } from 'tsyringe';
@injectable()
export class Test {
constructor() {
console.log('hi from test');
}
a(): void {
console.log('a');
}
b(): void {
console.log('b');
}
}
调用类
import React, { ReactElement } from 'react';
import Head from 'next/head';
import { Test } from '../_service/test.service';
import { inject } from '../decorators/inject';
/**
* @class Home
*/
export default class Home extends React.Component {
@inject(Test)
private readonly test!: Test;
/**
* Render Home
*
* @returns ReactElement<any>
*/
render(): ReactElement<any> {
this.test.a();
this.test.b();
return (
<div>
<Head>
<title>home</title>
</Head>
<main>
<p>test</p>
</main>
</div>
);
}
}
控制台输出
hi from test
a
hi from test
b
当前行为:每次调用注入类的方法时,都会再次调用构造函数。所以这意味着我的类在每次新调用时都会得到新的初始化。
当我使用以下代码时,一切似乎都在工作
import React, { ReactElement } from 'react';
import Head from 'next/head';
import { Test } from '../_service/test.service';
import { container } from 'tsyringe';
/**
* @class Home
*/
export default class Home extends React.Component {
private readonly test: Test = container.resolve(Test);
/**
* Render Home
*
* @returns ReactElement<any>
*/
render(): ReactElement<any> {
this.test.a();
this.test.b();
return (
<div>
<Head>
<title>home</title>
</Head>
<main>
<p>test</p>
</main>
</div>
);
}
}
控制台输出
hi from test
a
b
发生这种情况的任何原因?