可以从装饰器中的类中获取“ this”

Wmattei

我有一个打字稿类装饰器,我需要在Singleton上注入一个类实例,到目前为止,我拥有的是:

// provider.decorator.ts
import Injector from './injector';

export default function Provider<T extends { new (...args: any[]): {} }>(
    constructor: T
) {
    Injector.register('scope', constructor);
    return class extends constructor {};
}

// Very first instantiated class on the project
@Provider
export class ThoughtsInfraStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);
        const dynamo = new DynamoTables();
    }
}

这不起作用,因为构造函数不是类实例

我可以做的就是ThoughtInfraStack打电话给我的Singleton和inject this,但是我真的很想用一个装饰器来做。

埃尔达

您可以扩展该类的构造函数,并在其中添加注入逻辑:

function Provider<T extends { new(...args: any[]): {} }>(
    konstructor: T
) {
    const klass = class extends konstructor {
        constructor(...args: any[]) {
            super(args)
            Injector.register('scope', this);
        }
    }

    return klass;
}

游乐场链接

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章