iamdeit
iamdeit

Reputation: 6055

How to inject a nestjs service into another service when both belong to the same module?

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?

Upvotes: 7

Views: 12384

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70550

From your error, it looks like there's a circular dependency between your file imports. Check to make sure that you don't have a circular import chain going on (i.e. ServiceA imports ServiceB imports ServiceA or ServiceA imports ModuleA imports ServiceB imports ServiceA). This can especially become common common when using barrel files inside the same module.

Upvotes: 2

Related Questions