NestJS:如何将服务从同一模块注入到提供者中



是否可以将服务从同一模块注入工厂提供程序?我有一个服务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无法初始化所有依赖项,应用程序也无法运行。

有可能做这样的事情吗?

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

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

最新更新