gpt4 book ai didi

node.js - NestJS:如何从同一模块将服务注入(inject)提供者?

转载 作者:行者123 更新时间:2023-12-03 12:18:43 29 4
gpt4 key购买 nike

是否可以从同一模块将服务注入(inject)工厂提供者?我有一个服务 AppService,我想在下面的这个工厂提供者中使用。

这是我的代码:

app.module.ts

@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: 'List',
imports: [AnotherModule],
useFactory: (anotherService: AnotherService) => {
const schema = ListSchema;
schema.pre('save', function() {
// Validate
})
return schema;
},
inject: [AnotherService],
},
],
providers: [AppService],
exports: [AppService],
})
export class AppModule {}

我希望能够做这样的事情:

app.module.ts

@Module({
imports: [
MongooseModule.forFeatureAsync([
{
name: 'List',
imports: [AnotherModule, AppModule],
useFactory: (anotherService: AnotherService, appService: AppService) => {
const schema = ListSchema;
schema.pre('save', function() {
// Validate
})
return schema;
},
inject: [AnotherService, AppService],
},
],
providers: [AppService],
exports: [AppService],
})
export class AppModule {}

这是行不通的。 Nest 无法初始化所有依赖项,应用程序无法运行。

甚至可以做这样的事情吗?

如何将来自同一模块的服务注入(inject)到该工厂提供者中?一种解决方案是将该服务移动到不同的模块,然后注入(inject)该服务。但是,如果可能的话,我想避免这种情况。

最佳答案

不可能将当前模块中的服务添加到当前模块作为其 Bootstrap 的一部分导入的模块中,因为这将是两者之间的主要循环依赖。您也许可以通过一些有趣的 forwardRef() 函数来绕过它,但总的来说,应该避免这种模式,因为它会给代码库带来困惑

关于node.js - NestJS:如何从同一模块将服务注入(inject)提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61067426/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com