#Circular dependency error

12 messages · Page 1 of 1 (latest)

raw robin
#

I have an error when injecting services that depend on each other

heavy isleBOT
#

Suggestion for @raw robin:
Occasionally you'll find it difficult to avoid circular dependencies in your application.
You'll need to take some steps to help Nest resolve these. Errors that arise from circular dependencies look like this:

Nest cannot create the <module> instance.
The module at index [<index>] of the <module> "imports" array is undefined.

Potential causes:
- A circular dependency between modules. Use forwardRef() to avoid it.
- The module at index [<index>] is of type "undefined". Check your import statements and the type of the module.

Scope [<module_import_chain>]
# example chain AppModule -> FooModule

A circular dependency occurs when two classes depend on each other.
For example, class A needs class B, and class B also needs class A.
Circular dependencies can arise in Nest between modules and between providers.

While circular dependencies should be avoided where possible, you can't always do so.
In such cases, Nest enables resolving circular dependencies between providers in two ways.
In this chapter, we describe using forward referencing as one technique, and using the ModuleRef class to retrieve a provider instance from the DI container as another.

void basin
#

please show us AuthCodeService's constructor

raw robin
#

""import { Injectable } from '@nestjs/common';
import { Repository } from 'typeorm';
import { AuthCode } from './entities/auth-code.entity';
import { Merchant } from 'src/shared/entities/merchant.entity';

@Injectable()
export class AuthCodeService {
constructor(private readonly authCodeRepository: Repository<AuthCode>) {}

async findOne(type: string, merchant: Merchant) {
return this.authCodeRepository.findOneBy({ type, merchant });
}
}
""

raw robin
# void basin please show us `AuthCodeService`'s constructor

this was the fix that worked for me import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AuthCode } from './entities/auth-code.entity';
import { AuthCodeService } from './auth-code.service';
import { Repository } from 'typeorm';

@Module({
imports: [TypeOrmModule.forFeature([AuthCode])],
providers: [
AuthCodeService,
{
provide: Repository,
useClass: Repository,
},
],
})
export class AuthCodeModule {}

void basin
#

but you shouldn't be doing that
That's up to TypeOrmModule

#

that .forFeature() will register the providers you needed

raw robin
#

yeah I know but as soon as I remove the repository provider the app breaks

plucky vector
#

Why are you injecting using Repository<AuthCode> and not using the @InjectRepository(AuthCode) decorator?

#

Generics don't get reflection metadata properly, so Nest doesn't know you're using <AuthCode> with Repository

raw robin
#

I missed that..

#

thanks @plucky vector