Node.js NestJS:如何将服务从同一模块注入到提供者中?
是否可以从同一模块将服务注入工厂提供程序?我有一个服务Node.js NestJS:如何将服务从同一模块注入到提供者中?,node.js,typescript,mongoose,dependency-injection,nestjs,Node.js,Typescript,Mongoose,Dependency Injection,Nestjs,是否可以从同一模块将服务注入工厂提供程序?我有一个服务AppService,我想在下面的工厂提供程序中使用 这是我的密码: app.module.ts @Module({ imports: [ MongooseModule.forFeatureAsync([ { name: 'List', imports: [AnotherModule], useFactory: (anotherService:
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 {}
@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 {}
我希望能够做到以下几点:
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 {}
@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()
函数,但总体而言,应该避免这种模式,因为它会给代码库带来混乱谢谢,这是有意义的。我正在研究forwardRef()
,但正如您所指出的,这似乎不适合我正在尝试做的事情。我最好将逻辑移到一个单独的模块,然后注入它。谢谢你的帮助!