The official doc is not clear about how modules in nestjs work and I'm having a problem with a circular dependency. It seems like my module structure is messed up I would like to understand what is wrong with it. The error I'm getting reads:
Nest cannot create the module instance. Often, this is because of a circular dependency between modules. Use forwardRef() to avoid it. (Read more: https://docs.nestjs.com/fundamentals/circular-dependency) Scope [AppModule -> UsersModule -> CategoriesModule]
Here are the import parts of all the modules mentioned in the error message.
AppModule:
UsersModule,
SmsRegistrationModule,
AuthModule,
SubscriptionModule,
EmailModule,
EntriesModule,
CategoriesModule,
AwsModule,
SharedModule
UsersModule:
CategoriesModule
CategoriesModule:
AwsModule,
SharedModule,
The error raised when I added SharedModule
to the CategoriesModule
module. Seems like I'm missing something on how these modules communicate and thus can't resolve this error.
Your help would be much apprecicted.
EDIT:
SharedModule:
@Module({
providers: [
CacheService,
CodeGenService,
IsUniqueEmail,
BasicFileService,
],
imports: [
CacheModule.registerAsync({
imports: [ConfigModule],
useClass: CacheConfigService,
}),
UsersModule,
AwsModule,
],
exports: [
CacheService,
CodeGenService,
IsUniqueEmail,
BasicFileService,
],
})
export class SharedModule {}
Your SharedModule
imports UserModule
, so the import chain (or at least the one I'm going to follow here) is AppModule -> UsersModule -> CategoriesModule -> SharedModule -> UsersModule -> CategoriesMOdule -> SharedModule -> ...
. To get around this, either the SharedModule
should not import the UsersModule
, or you should forward reference the CategoriesModule
from the UserModule
, the UserModule
from the SharedModule
and the SharedModule
from the CategoriesModule
. This is my first time seeing a circular dependency a few modules deep, so I can't give the exact syntax of how to work with the forwardRef
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With