/nest-dependency-injection-issue

Example of NestJS dependency injection not resolving to the correct singleton instance

Primary LanguageTypeScript

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

Nest Logo

A progressive Node.js framework for building efficient and scalable server-side applications.

NPM Version Package License NPM Downloads CircleCI Coverage Discord Backers on Open Collective Sponsors on Open Collective Support us

Description

Nest framework TypeScript starter repository.

Installation

$ npm install

Running the app

# development
$ npm run start

# watch mode
$ npm run start:dev

# production mode
$ npm run start:prod

Test

# unit tests
$ npm run test

# e2e tests
$ npm run test:e2e

# test coverage
$ npm run test:cov

Support

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.

Stay in touch

License

Nest is MIT licensed.