【问题标题】:MongooseModule.forRootAsync - can't resolve depenciesMongooseModule.forRootAsync - 无法解决依赖关系
【发布时间】:2020-07-01 21:34:42
【问题描述】:

我正在尝试使用 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 {
}

很简单(忽略 Op 名称,稍后我会在需要的地方移动它)

这里是EndpointsService

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

  constructor() {
....

但 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

我也尝试在Op 类中使用不带forwardRef 的常规注入,但结果是一样的。

我错过了什么?

【问题讨论】:

    标签: mongoose nestjs


    【解决方案1】:

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

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

    在这种情况下,EndpointsService 属于AppModule,但AppModule 不会导入到MongooseModule 中进行配置(这会很混乱,因为这是一个主要的循环依赖项)。你应该做的是创建一个EndpointsModule providesexports EndpointsService 像这样:

    @Module({
      providers: [EndpointsService],
      exports: [EndpointsService],
    })
    export class EndpointsModule
    

    现在在您的MongooseModule 中,您可以像这样进行异步配置

    MongooseModule.forRootAsync({
      imports: [EndpointsModule],
      useClass: Op,
    })
    

    【讨论】:

    • 我并不想添加一个新模块,但看起来没有它是行不通的。现在可以使用新模块。 :)
    • 我遵循这样的理念,“如果它是一个特性,它就需要一个模块”。老实说,到目前为止一切都很好
    猜你喜欢
    • 2016-02-16
    • 2017-02-20
    • 2018-05-25
    • 2019-09-14
    • 2016-02-13
    相关资源
    最近更新 更多