有没有办法在NestJS中使用带有依赖注入的静电方法? [英] Is there a way to use static method with dependency injection in NestJS?

查看:83
本文介绍了有没有办法在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();
    /* ... */
  }
}
// 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()以使用依赖项注入,以便轻松进行测试,例如?

推荐答案

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

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

这篇关于有没有办法在NestJS中使用带有依赖注入的静电方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆