有没有办法在 NestJS 中使用静态方法和依赖注入?

web*_*dif 7 javascript dependency-injection node.js nestjs

一个例子比长篇大论更好:

// 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();
    /* ... */
  }
}
Run Code Online (Sandbox Code Playgroud)
// 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 :(
  }
}
Run Code Online (Sandbox Code Playgroud)

BakeryService.myStaticMethodToGetPrice()例如,我如何替换为使用依赖注入,以便我可以轻松地进行测试?

Jay*_*iel 6

静态方法不能使用依赖注入。这是因为依赖项注入(至少对于 Nest 来说)的想法是注入依赖项的实例,以便以后可以利用它们。

您拥有的代码是有效的,因为它将返回1像静态方法所说的值,但静态方法不能使用注入的任何实例值。您会发现大多数其他 DI 框架都遵循这种逻辑。