Home > Net >  Why cant nestj resolve dependencies?
Why cant nestj resolve dependencies?

Time:12-11

So i have a Nest application and have gotten stuck on what feels like a very basic issue.

I need to use the PlaceVerificationRequestService in the PlaceService but cant inject it properly without receiving the following error:

Nest can't resolve dependencies of the PlaceService (PlaceRepository, ClientService, ?). Please make sure that the argument dependency at index [2] is available in the PlaceModule context.

My approach has been to just follow the same style as i did when importing & injecting the ClientService in to PlaceService but still it does not work and i cant figure out why.

This is my code.

place.module.ts

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [Place, Client, PlaceVerificationRequest],
    }),
  ],
  providers: [PlaceService, ClientService, PlaceVerificationRequestService],
  controllers: [PlaceController],
  exports: [PlaceService],
})

place-verification-request.module.ts

@Module({
  imports: [
    MikroOrmModule.forFeature({
      entities: [PlaceVerificationRequest, Client, Place],
    }),
  ],
  providers: [PlaceVerificationRequestService, ClientService, PlaceService],
  controllers: [PlaceVerificationRequestController],
  exports: [PlaceVerificationRequestService],
})

place.service.ts

@Injectable()
export class PlaceService {
  constructor(
    @InjectRepository(Place)
    private readonly placeRepo: EntityRepository<Place>,
    private readonly clientService: ClientService,
    private readonly reqService: PlaceVerificationRequestService,
  ) {}

It feels like im missing something that is right in front of my nose since it feels very basic but i cant seem to spot it. Anyone that has a clue? thanks

CodePudding user response:

Okay after 5 hours, the trick is... to read the docs.

Nest can't resolve dependencies of the <provider> (?). Please make sure that the argument <unknown_token> at index [<index>] is available in the <module> context.

Potential solutions:
- If <unknown_token> is a provider, is it part of the current <module>?
- If <unknown_token> is exported from a separate @Module, is that module imported within <module>?
  @Module({
    imports: [ /* the Module containing <unknown_token> */ ]
  })
If the unknown_token above is the string dependency, you might have a circular file import. 

(gotta admit they could've come up with a clearer error message)

So basically the problem was that PlaceService was getting injected in PlaceVerificationRequestService and PlaceVerificationRequestService was getting injected in PlaceService so the trick is to use forwardRef:

PlaceVerificationRequestService

@Inject(forwardRef(() => PlaceService))
private readonly placeService: PlaceService,

PlaceService

@Inject(forwardRef(() => PlaceVerificationRequestService))
private readonly reqService: PlaceVerificationRequestService,
  • Related