Richa Khetan
Richa Khetan

Reputation: 37

Nest can't resolve dependencies of the Service while compiling nest project

Getting below error while compiling the below code: I am new to nestjs and this is the attached sample application code. I tried replacing UsersService in module.ts with UsersModule as well but it didn't work. What am i doing wrong ?

 [Nest] 19960 - 10/19/2020, 11:42:09 PM [NestFactory] Starting Nest application...
[Nest] 19960 - 10/19/2020, 11:42:09 PM [InstanceLoader] MongooseModule dependencies initialized +25ms
[Nest] 19960 - 10/19/2020, 11:42:09 PM [InstanceLoader] PassportModule dependencies initialized +1ms
[Nest] 19960 - 10/19/2020, 11:42:09 PM [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is available in the AuthService context.

Potential solutions:

If UsersService is a provider, is it part of the current AuthService?
If UsersService is exported from a separate @module, is that module imported within AuthService?
@module({
imports: [ /* the Module containing UsersService */ ]
})

Repoistory : https://github.com/richakhetan/task-manager-nest

Upvotes: 1

Views: 2373

Answers (2)

Richa Khetan
Richa Khetan

Reputation: 37

modules were not properly structured. I removed the code causing circular dependency from the modules and created a new module creating a clear structure.

Detailed Code can be found in the repository. Repository : https://github.com/richakhetan/task-manager-nest

Upvotes: 0

Jay McDoniel
Jay McDoniel

Reputation: 70061

You have a circular dependency between the AuthModule and UserModule and between the UserService and AuthService. To resolve this, on both the modules and the services you need to use a forwardRef. Generally, this would just look like

@Module({
  imports: [forwardRef(() => UserModule)],
  providers: [AuthService],
  exports: [AuthService],
})
export class AuthModule {}
@Module({
  imports: [forwardRef(() => AuthModule)],
  providers: [UserService],
  exports: [UserService],
})
export class UserModule {}
@Injectable()
export class AuthService {
  constructor(@Inject(forwardRef(() => UserService)) private readonly userService: UserService) {}
}
@Injectable()
export class UserService {
  cosntructor(@Inject(forwardRef(() => AuthService) private readonly authService: AuthService) {}
}

Edit

Forgot to add the exports property

Upvotes: 1

Related Questions