I have the following scenario in NestJS:
// user.service.ts
@Injectable()
export class UserService {
constructor(
private readonly userRepository: UserRepository,
private readonly userProfileService: UserProfileService,
) {}
}
// user-profile.service.ts
@Injectable()
export class UserProfileService {
constructor(
private readonly userProfileRepository: UserProfileRepository,
) {}
}
// user.module.ts
@Module({
imports: [DataRepositoryModule], // Required for the repository dependencies
providers: [UserService, UserProfileService],
exports: [UserService, UserProfileService],
})
export class UserModule {}
However, when I try to use the UserService inside a controller from another module, I get the following error:
Nest can't resolve dependencies of the UserService (UserRepository, ?). Please make sure that the argument dependency at index [1] is available in the UserModule context.
Potential solutions:
- If dependency is a provider, is it part of the current UserModule?
- If dependency is exported from a separate @Module, is that module imported within UserModule?
@Module({
imports: [ /* the Module containing dependency */ ]
})
Controller code:
@Controller()
export class UserController {
constructor(private readonly userService: UserService) {}
}
Controller module:
@Module({
imports: [],
providers: [],
controllers: [UserController],
})
export class UserManagementModule {}
Main app.module.ts:
@Module({
imports: [
UserManagementModule,
UserModule,
DataRepositoryModule.forRoot(),
],
controllers: [],
providers: [],
})
export class AppModule {}
I'm confused because I'm doing exactly what the error suggests, adding both services inside the providers array (UserModule). What could I be missing?