MongooseModule.forRootAsync - 无法解析依赖关系

Eug*_*gen 1 mongoose nestjs

我正在尝试使用 mongoose 并按照 Nestjs.com 中的相同内容动态配置连接,但在我的情况下,我需要注入工厂的服务将无法解析。这里是AppModule

@Injectable()
class Op implements MongooseOptionsFactory {
  constructor(
    @Inject(forwardRef(() => EndpointsService))
    private endpointsService: EndpointsService) {
  }

  createMongooseOptions(): MongooseModuleOptions {
    return {
      uri: this.endpointsService.loginMongoDb
    };
  }
}

@Module({
  imports: [
    MongooseModule.forRootAsync({
      useClass: Op,
      inject: [EndpointsService] // having this doesn't help either
    })
  ],
  controllers: [AppController, UserController],
  providers: [AppService, 
    EndpointsService, // is in the core module, but won't be seen
    UserService]
})
export class AppModule {
}

Run Code Online (Sandbox Code Playgroud)

非常简单(忽略操作名称,我稍后会将其移动到需要的地方)

这是EndpointsService

@Injectable()
export class EndpointsService {
  private readonly _loginApi: string;
  private readonly _loginMongoDb: string;

  constructor() {
....
Run Code Online (Sandbox Code Playgroud)

但 ap 无法启动,并出现错误

[Nest] 83842   - 03/20/2020, 10:54:26 AM   [NestFactory] Starting Nest application...
[0] [Nest] 83842   - 03/20/2020, 10:54:26 AM   [InstanceLoader] MongooseModule dependencies initialized +14ms
[0] [Nest] 83842   - 03/20/2020, 10:54:26 AM   [ExceptionHandler] Nest can't resolve dependencies of the Op (?). Please make sure that the argument EndpointsService at index [0] is available in the MongooseCoreModule context.
[0] 
[0] Potential solutions:
[0] - If EndpointsService is a provider, is it part of the current MongooseCoreModule?
[0] - If EndpointsService is exported from a separate @Module, is that module imported within MongooseCoreModule?
[0]   @Module({
[0]     imports: [ /* the Module containing EndpointsService */ ]
[0]   })
[0]  +0ms

Run Code Online (Sandbox Code Playgroud)

我也尝试过forwardRefOp类中不使用常规注入,但结果是一样的。

我缺少什么?

Jay*_*iel 5

要将服务注入异步配置,该服务或提供者必须是

  1. 通过模块导入在模块范围内
  2. 通过全局模块提供的全局服务

在这种情况下,EndpointsService属于AppModule,但AppModule没有导入到MongooseModulefor 配置中(这会很混乱,因为这是一个主要的循环依赖)。相反,你应该做的是创建一个EndpointsModulethatprovidesexportsEndpointsService的:

@Module({
  providers: [EndpointsService],
  exports: [EndpointsService],
})
export class EndpointsModule
Run Code Online (Sandbox Code Playgroud)

现在MongooseModule你可以像这样进行异步配置

MongooseModule.forRootAsync({
  imports: [EndpointsModule],
  useClass: Op,
})
Run Code Online (Sandbox Code Playgroud)