【发布时间】:2021-05-05 19:20:49
【问题描述】:
我尝试将 NestJs 模块的控制器模块与域模块分离(根据干净架构原则),以便依赖项仅流向域。 我不明白如何让它工作,没有注入 repo 接口的实现(嵌套开始时出错)。
这是模块结构:
AppModule -> CommunityControllerModule -> DomainModule
(provides repoImpl (has service requiring an unknown
by token) concrete repo interface impl)
社区控制器模块:
import { DomainModule } from 'libs/domain/src';
import { Module } from '@nestjs/common';
import { CommunityController } from './community.controller';
import { CommunityRepositoryImpl } from './community.repository';
@Module({
imports: [DomainModule, CommunityRepositoryImpl],
controllers: [CommunityController],
exports: [CommunityRepositoryImpl],
providers: [
{
provide: 'CommunityRepository',
useClass: CommunityRepositoryImpl,
},
],
})
export class CommunityControllerModule {}
域模块:
import { Module } from '@nestjs/common';
import { CommunityService } from './community.service';
@Module({
providers: [CommunityService],
exports: [CommunityService],
})
export class DomainModule {}
注入失败的社区服务:
import { HttpException, HttpStatus, Inject, Injectable } from '@nestjs/common';
import { CommunityRepository } from './community.repo';
@Injectable()
export class CommunityService {
constructor(
@Inject('CommunityRepository') private repo: CommunityRepository,
) {}
}
输出的错误:
> nest start
webpack 5.28.0 compiled successfully in 8218 ms
[Nest] 7204 - 2021-05-05 20:52:05 [NestFactory] Starting Nest application...
[Nest] 7204 - 2021-05-05 20:52:05 [InstanceLoader] CommunityRepositoryImpl dependencies initialized +49ms
[Nest] 7204 - 2021-05-05 20:52:05 [ExceptionHandler] Nest can't resolve dependencies of the CommunityService (?). Please make sure that the argument CommunityRepository at index [0] is available in the DomainModule context.
Potential solutions:
- If CommunityRepository is a provider, is it part of the current DomainModule?
- If CommunityRepository is exported from a separate @Module, is that module imported within DomainModule?
@Module({
imports: [ /* the Module containing CommunityRepository */ ]
})
【问题讨论】: