服务解析在NestJS中如何工作?

时间:2019-10-18 02:35:29

标签: nestjs

我是NestJS的新手,我经常与它的服务解析器搏斗,所以我想了解它如何解析服务,以期使使用NestJS的整个体验不再令人沮丧。

此问题源于我对特定提供者的解决存在的奇怪(对我而言)问题。想象一下,我有一个非常简单的模块:

- src
  - game
    - game.module.ts
    - game.repository.ts

然后我的模块如下所示:

@Module({
  imports: [TypeOrmModule.forFeature([Game])],
  providers: [GameRepository],
})
export class GameModule {
}

我的GameRepository类(在game.repository.ts中)如下所示:

@Injectable()
export class GameRepository {
  public constructor(
    @InjectRepository(Game)
    private readonly gameRepository: Repository<Game>,
  ) {}
}

这将拒绝编译。我会得到的错误是:[ExceptionHandler] Nest can't resolve dependencies of the GameRepository (?). Please make sure that the argument at index [0] is available in the GameModule context. +64ms

那时候,我想也许它使用文件名来确定实例化该类的方式,所以我将该类重命名为GameService,并将文件重命名为game.service.ts,然后瞧瞧,现在NestJS很高兴能够成功编译!

除了...为什么?从错误消息来看,这不应该是问题,而且,我不确定NestJS使用文件名或类名做出任何决定是否有意义。

我的理解(此时显然是错误的)是,@Injectable注释决定了服务容器将实例化哪些类,然后模块providers数组中的任何内容都将被实例化,并且依赖注入。但是从上述情况来看,这似乎并不是全部。


因此,所有这些要说的是,该文档没有一节详细介绍了IoC背后的逻辑,我想了解它。

0 个答案:

没有答案