问题描述
上下文是,我创建了一个共享的配置模块,该模块导入了多个配置模块,每个配置模块都在导出自己的服务,共享模块导出了每个导入的模块,目前在我的应用程序中,我有要导入的应用程序模块共享配置模块和导入共享配置模块的auth模块。
在项目中,我正在使用nestjs微服务,并且尝试使用ClientsModule
方法注册registerasync
来访问我的auth模块中的auth config服务。
目录体系结构:
/**
config/
- shared-config.module.ts
- app/
- app-config.service.ts
- app-config.module.ts
- auth/
- auth-config.service.ts
- auth-config.module.ts
... other config modules
- auth/
- auth.module.ts
- app/
- app.module.ts
*/
shared-config.module.ts:
@Module({
imports: [AppConfigModule,MicroServiceAuthConfigModule,/* and other modules */],export: [AppConfigModule,/* and other modules */]
})
export class SharedConfigModule {}
auth-config.module.ts:
@Module({
imports: [
ConfigModule.forRoot({
... some config
}),],providers: [MicroServiceAuthConfigService],exports: [MicroServiceAuthConfigService],})
export class MicroServiceAuthConfigModule {}
问题是我试图使用MicroServiceAuthConfigService
在我的ClientsModule
中创建AuthModule
。
auth.module.ts:
@Module({
imports: [
SharedConfigModule,ClientsModule.registerasync([
{
name: 'AUTH_PACKAGE',inject: [MicroServiceAuthConfigService],useFactory: (authConfigService: MicroServiceAuthConfigService) => ({
transport: Transport.GRPC,options: {
url: authConfigService.url,package: authConfigService.package,protoPath: authConfigService.protoPath,},}),]),controllers: [AuthController],providers: [AuthService],})
export class AuthModule {}
app.module.ts:
@Module({
imports: [AuthModule,SharedConfigModule],})
export class AppModule {}
因为我已经导入了SharedConfigModule,所以我应该访问useFactory
中的MicroServiceAuthConfigService,但是却出现以下错误:
嵌套无法解析AUTH_PACKAGE(?)的依赖项。请做出来 确保索引[0]处的参数MicroServiceAuthConfigService为 在ClientsModule上下文中可用。
可能的解决方案:
奇怪的是,在我的应用模块中,我注入了SharedConfigModule
,在文件main.ts
中,我正在使用app.get(MicroServiceAuthConfigService)
,并且可以正常工作。
那我在做什么错了?
解决方法
在您的ClientsModule.registerAsync
中,需要添加imports
,其数组包含导出MicroServiceAuthConfigService
提供程序的模块。看起来您特别需要
@Module({
imports: [
SharedConfigModule,ClientsModule.registerAsync([
{
name: 'AUTH_PACKAGE',imports: [MicroServiceAuthConfigModule],inject: [MicroServiceAuthConfigService],useFactory: (authConfigService: MicroServiceAuthConfigService) => ({
transport: Transport.GRPC,options: {
url: authConfigService.url,package: authConfigService.package,protoPath: authConfigService.protoPath,},}),]),],controllers: [AuthController],providers: [AuthService],})
export class AuthModule {}