Nest.js 未找到依赖倒置函数

Nest.js Dependency Inversion function not found

我遵循了controller-service-repository架构,我想在StoneRepository上使用依赖倒置。有了下面的代码,我得到:

[Nest] 22656  - 03/21/2022, 5:01:44 PM   ERROR [ExceptionsHandler] this.stoneRepository.getStones is not a function

我做错了什么? 请帮忙。

constants.ts

export const STONE_REPOSITORY_TOKEN = Symbol("STONE_REPOSITORY_TOKEN");

app.module.ts

import { Module } from "@nestjs/common";
import { AppController } from "./app.controller";
import { AppService } from "./app.service";
import { StoneModule } from "./stone/stone.module";
  
@Module({
  imports: [StoneModule],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

stone.module.ts

import { Module } from "@nestjs/common";
import { StoneController } from "./stone.controller";
import { StoneService } from "./stone.service";
import { StoneRepository } from "./stone.repository";
import { STONE_REPOSITORY_TOKEN } from "./constants";

@Module({
  imports: [],
  controllers: [StoneController],
  providers: [
    {
      provide: STONE_REPOSITORY_TOKEN,
      useValue: StoneRepository,
    },
    StoneService,
  ],
})
export class StoneModule {}

stone.controller.ts

import { Controller, Get } from "@nestjs/common";
import { StoneService } from "./stone.service";
import { Stone } from "./domain/Stone";

@Controller()
export class StoneController {
  constructor(private stoneService: StoneService) {}

  @Get("/stone")
  async getStones(): Promise<Stone[]> {
    return await this.stoneService.getStones();
  }
}

stone.interface.repository.ts

import { Stone } from "./domain/Stone";

export interface StoneInterfaceRepository {
  getStones(): Promise<Stone[]>;
}

stone.service.ts

import { Inject, Injectable } from "@nestjs/common";
import { StoneInterfaceRepository } from "./stone.interface.repository";
import { Stone } from "./domain/Stone";
import { STONE_REPOSITORY_TOKEN } from "./constants";

@Injectable()
export class StoneService {
  constructor(
    @Inject(STONE_REPOSITORY_TOKEN)
    private stoneRepository: StoneInterfaceRepository,
  ) {}
  async getStones(): Promise<Stone[]> {
    return await this.stoneRepository.getStones();
  }
}

stone.repository.ts

import { Injectable } from "@nestjs/common";
import { StoneInterfaceRepository } from "./stone.interface.repository";
import { Stone } from "./domain/Stone";

@Injectable()
export class StoneRepository implements StoneInterfaceRepository {
  async getStones(): Promise<Stone[]> {
    return Promise.resolve([new Stone()]);
  }
}

您正在使用 useValue 作为 STONE_REPOSITORY_TOKEN 令牌的自定义提供商。这意味着 Nest 将注入直接引用,而不是 class 实例,因此您无法访问实例方法,例如 getStones()。将您的模块更改为:

@Module({
  imports: [],
  controllers: [StoneController],
  providers: [
    {
      provide: STONE_REPOSITORY_TOKEN,
      useClass: StoneRepository,
    },
    StoneService,
  ],
})
export class StoneModule {}