midwayjs / injection

Injection is a powerful inversion of control container that is widely used in the midway framework and brings good user experience.
MIT License
160 stars 20 forks source link

请问使用装饰器@provider(key)注入的依赖如何获取? #15

Closed zzyyzz1992 closed 5 years ago

zzyyzz1992 commented 5 years ago

Midway里面的Container或者MidwayContainer如果new一个的话里面是空的. 请问如何获取使用Midway的provider装饰对应的Container? 谢谢!

zzyyzz1992 commented 5 years ago

找到了,方便后来人参考: 动态函数注入

export function containerFactory(context: IApplicationContext) {
    return async (name: string) => {
        return await context.getAsync(name);
    };
};
providerWrapper([
    {
        id: 'containerFactory',
        provider: containerFactory
    }
]);
 @inject('containerFactory')
    containerFactory;
czy88840616 commented 5 years ago

如果是请求作用域,也可以通过 ctx.requestContext 获取,静态作用域,使用 app.applicationContext,不过一般情况下用不到。