1

一个例子胜过冗长的解释:

// 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 :(
  }
}

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

4

2 回答 2

2

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

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

于 2021-01-22T17:18:13.103 回答
1

有一种非常简单的方法可以创建使用 NestJs DI 中的服务的静态函数。

一个很好的例子是使用领域事件并避免使用技术服务污染实体的构造函数。

在你的 main.ts

let app: INestApplication;

async function bootstrap() {
  app = await NestFactory.create(AppModule);

  install();
  ...
  ...
}

bootstrap();

export const getInstance = () => {
  return app;
};

从您的应用程序中的任何静态上下文中:

import { getInstance } from '@/main';

static async emmitEvent() {
    let eventEmitter = await getInstance().resolve(EventEmitter2);
    eventEmitter.emit(JSON.stringify(nodeCreateEvent));
}
于 2021-06-21T07:26:21.853 回答