'Dependency injection problem with gateways and other modules

I'm using nestjs from a while and I found it very useful, expecially when projects grow in size and complexity.

However, I'm having a problem with dependency injection. I've always used it between modules of the same type (REST modules).

I followed the procedure as described in the website, exporting the desired service from this module

@Module({
  imports: [TypeOrmModule.forFeature([Bs]), forwardRef(() => WineModule)],
  controllers: [BsController],
  providers: [BsService],
  exports: [BsService],
})
export class BsModule {}

and importing in another module

@Module({
  imports: [BsModule],
  providers: [WebsocketGateway, WebsocketService],
  exports: [WebsocketGateway],
})
export class WebsocketModule {}

Thanks to a previous post I discovered that I need to export the service but i need to import the module. I used this path for 5 or 6 modules and I've never had problems.

Unfortunately if I try to import something into a gateway module (used for socket.io) I'm not able to compile because I receive an error about a circular dependency.

Usually with other modules I solved that problem using a forwardRef, however with gateway even if i use this strategy it seems that it's not able to recognize the import and it throws an error saying that it cannot find the module or the service in the constructor.

I searched for some topic about, maybe nestjs avoid the import and dependency injection from different kind of services (rest to gateway or viceversa), but I didn't find nothing helpful.

Sorry for typos but I'm trying to improve my english!

thank you

D.



Solution 1:[1]

Due this: " it throws an error saying that it cannot find the module or the service in the constructor." Your exporting of BS Module is right and importing of WebSocketModule is right too. The wrong path I think is in the WebsocketGateWay I just meet this case and my solution is:

  • Check the service that you inject BsService
  • Try to remove some injection in that service, some of them may cause the Module to be Undefined
  • In my case, I use @Inject(REQUEST) private request: Request so this is only for HTTP Request but I am using socket in Gateway. When I delete that, it works smoothly

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bùi Anh Khoa