Skip to content
Advertisement

Is there a way to use static method with dependency injection in NestJS?

An example is better than a long explanation:

// Backery.service.ts
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Backery } from './Backery.entity';

@Injectable()
export class BackeryService {
  constructor(
    @InjectRepository(Backery)
    private readonly backeryRepository: Repository<Backery>,
  ) {}

  static myStaticMethodToGetPrice() {
    return 1;
  }

  otherMethod() {
    this.backeryRepository.find();
    /* ... */
  }
}
// Backery.resolver.ts
import { Bakery } from './Bakery.entity';
import { BakeryService } from './Bakery.service';

@Resolver(() => Bakery)
export class BakeryResolver {
  constructor() {}

  @ResolveField('price', () => Number)
  async getPrice(): Promise<number> {
    return BakeryService.myStaticMethodToGetPrice(); // No dependency injection here :(
  }
}

How can I replace BakeryService.myStaticMethodToGetPrice() to use dependency injection, so I can test things easily for example?

Advertisement

Answer

Static methods cannot use dependency injection. This is because the idea of dependency injection (at least to Nest) is to inject instances of the dependencies so that they can be leveraged later.

The code you have is valid, in that it will return the value 1 like the static method says to, but the static method cannot use any of the instance values that are injected. You’ll find this kind of logic follows in most other DI frameworks.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement