Example of NestJS (version 9.X) dependency injection not resolving to the correct singleton instance.
Given the following class diagram and making BService declare the constructor dependencies in a different order than CService (i.e. declaring the AService dependency BEFORE the IDatabaseProvider dependency):
classDiagram
BaseEntityService --> IDatabaseProvider
<<interface>> IDatabaseProvider
AService <-- BService
AService <-- CService
BaseEntityService <|-- AService
BaseEntityService <|-- BService
BaseEntityService <|-- CService
@Injectable()
export class BService extends BaseEntityService {
constructor(
public aService: AService,
@Inject(DATABASE_PROVIDER) public database: IDatabaseProvider,
) {
super(database);
}
}
@Injectable()
export class CService extends BaseEntityService {
constructor(
@Inject(DATABASE_PROVIDER) public database: IDatabaseProvider,
public aService: AService,
) {
super(database);
}
}
Then the BService singleton instance is generated before the AService singleton instance, and the AService instance injected to the BService singleton instance is not the AService singleton instance exported in AModule:
16:49:25.157 Instantiating BService
16:49:25.161 Instantiating AService
16:49:25.162 Instantiating CService
16:49:25.162 Is AService instance the AService singleton instance?
BService: false
CService: true
A progressive Node.js framework for building efficient and scalable server-side applications.
Nest framework TypeScript starter repository.
$ npm install
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please read more here.
- Author - Kamil Myśliwiec
- Website - https://nestjs.com
- Twitter - @nestframework
Nest is MIT licensed.