【发布时间】:2020-03-30 08:39:11
【问题描述】:
假设我有两个模块正在导出 BService 和 CService,这两个服务都扩展了 AService
所以代码如下所示:
abstract class AService {
public run() {}
}
@Injectable()
export class BService extends AService {}
@Injectable()
export class CService extends AService {}
@Module({
providers: [BService],
exports: [BService],
})
export class BModule {}
@Module({
providers: [CService],
exports: [CService],
})
export class CModule {}
@Injectable()
class AppService {
constructor(protected readonly service: AService) {}
public run(context: string) { // let's assume context may be B or C
this.service.run();
}
}
@Module({
imports: [CModule, BModule],
providers: [{
provide: AppService,
useFactory: () => {
return new AppService(); // how to use BService/CService depending on the context?
}
}]
})
export class AppModule {}
但关键是,我不能使用 @nestjs/core 中的 REQUEST(直接将其注入 useFactory),因为我在 cron 作业和 API 调用中使用此服务
我也不认为Factory 模式在那里有用,我的意思是它会起作用,但我想正确地做到这一点
但我不确定如何在我的情况下使用它
【问题讨论】:
-
在下面查看我的答案,看看它是否符合您的需求。这听起来像是使用策略模式的好地方。 stackoverflow.com/a/69502460/8148483
标签: javascript node.js typescript dependency-injection nestjs