【问题标题】:I'd like to DI for repository interface and service interface like Spring using typedi我想使用 typedi 为存储库接口和服务接口(如 Spring)进行 DI
【发布时间】:2021-08-25 00:13:34
【问题描述】:

我想使用 typedi 为存储库接口和服务接口(如 Spring)进行 DI。

以下代码(存储库的 DI 示例代码)在调用 api 时正常工作。

存储库

import { Service } from "typedi";
import { EntityRepository, Repository } from "typeorm";
import { User } from "../entity/User";

export interface IUserRepository {
  findAllUsers();

  findUserByUserId(id: number);

  addUser(user: any);

  removeUserByUserId(user: any);
}

@Service()
@EntityRepository(User)
export class UserRepository
  extends Repository<User>
  implements IUserRepository {
  findAllUsers() {
    return this.find();
  }

  findUserByUserId(id: number) {
    return this.findOne({ id });
  }

  addUser(user: any) {
    return this.save(user);
  }

  removeUserByUserId(user: any) {
    return this.remove(user);
  }
}

服务

import { Service } from "typedi";
import { InjectRepository } from "typeorm-typedi-extensions";
import { User } from "../entity/User";
import { UserRepository } from "../repository/userRepository";

export interface IUserService {
  all();

  one(id: any);

  save(user: any);

  remove(id: any);
}

@Service()
export class UserService implements IUserService {
  @InjectRepository(User)
  private userRepository: UserRepository;

  async all() {
    return this.userRepository.findAllUsers();
  }

  async one(id: any) {
    let user = await this.userRepository.findUserByUserId(id);
    if (typeof user === "undefined") {
      throw new Error(`userId ${id} is not found.`);
    }
    return user;
  }

  async save(user: any) {
    return this.userRepository.addUser(user);
  }

  async remove(id: any) {
    let userToRemove = await this.userRepository.findUserByUserId(id);
    if (typeof userToRemove === "undefined") {
      throw new Error(`userId ${id} is not found.`);
    }
    return this.userRepository.removeUserByUserId(userToRemove);
  }
}

但是,当我想使用接口注入存储库时,它无法正常工作并出现错误消息。
构建成功。调用api时出现错误信息
另外,第一次和第二次调用api时的错误信息不同。
像这样

存储库


import { Service } from "typedi";
import { InjectRepository } from "typeorm-typedi-extensions";
import { User } from "../entity/User";
import { UserRepository } from "../repository/userRepository";

...

@Service()
export class UserService implements IUserService {
  @InjectRepository(User)
  private userRepository: UserRepository;

  async all() {
    return this.userRepository.findAllUsers();
  }

  ...
}

第一次的错误信息。

{
  "name": "CustomRepositoryNotFoundError",
  "message": "Custom repository Object was not found. Did you forgot to put @EntityRepository decorator on it?",
  "stack": "CustomRepositoryNotFoundError: Custom repository Object was not found. Did you forgot to put @EntityRepository decorator on it? (The following is omitted)"
}

稍后第二次的错误信息。

{
  "name": "TypeError",
  "message": "Cannot read property 'all' of undefined",
  "stack": "TypeError: Cannot read property 'all' of undefined(The following is omitted)"
}

服务也不好。

下面的代码是成功代码。

控制器

import {
  Get,
  JsonController,
  OnUndefined,
  Param,
  Post,
  Body,
  Delete,
} from "routing-controllers";
import { Inject, Service } from "typedi";
import { UserService } from "../service/userService";

@Service()
@JsonController("/users")
export class UserRestController {
  @Inject()
  private userService: UserService;

  @Get("/")
  getAll() {
    return this.userService.all();
  }

  @Get("/:id")
  @OnUndefined(404)
  getOne(@Param("id") id: number) {
    return this.userService.one(id);
  }

  @Post("/")
  add(@Body() user: any) {
    return this.userService.save(user);
  }

  @Delete("/:id")
  delete(@Param("id") id: number) {
    return this.userService.remove(id);
  }
}

但下面的工作并不好。 在这种情况下,即使构建也不起作用。

控制器

import {
  Get,
  JsonController,
  OnUndefined,
  Param,
  Post,
  Body,
  Delete,
} from "routing-controllers";
import { Inject, Service } from "typedi";
import { IUserService } from "../service/userService";

@Service()
@JsonController("/users")
export class UserRestController {
  @Inject()
  private userService: IUserService;

  @Get("/")
  getAll() {
    return this.userService.all();
  }

  @Get("/:id")
  @OnUndefined(404)
  getOne(@Param("id") id: number) {
    return this.userService.one(id);
  }

  @Post("/")
  add(@Body() user: any) {
    return this.userService.save(user);
  }

  @Delete("/:id")
  delete(@Param("id") id: number) {
    return this.userService.remove(id);
  }
}

错误信息

CannotInjectValueError: Cannot inject value into "UserRestController.userService". Please make sure you setup reflect-metadata properly and you don't use interfaces without service tokens as injection value.

如开头所述,我想使用 typedi 为存储库接口和服务接口(如 Spring)进行 DI。
TypeDI不能这样使用? 还是我的代码错了? 请帮帮我。
谢谢。

【问题讨论】:

    标签: node.js typescript dependency-injection typedi


    【解决方案1】:

    接口是短暂的,当您的代码运行时它们实际上并不存在,它们仅在您编写代码时才存在。另一方面,类几乎是有形的,它们总是存在的。这就是为什么当你使用UserService类时,它可以工作,但当你使用IUserService接口时,它就不起作用了。

    你得到的错误告诉你一些有用的东西:

    请确保 […] 您不使用没有服务令牌的接口作为注入值。

    【讨论】:

      猜你喜欢
      • 2012-03-13
      • 2019-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-20
      • 2014-12-04
      • 2016-07-31
      • 2015-02-13
      相关资源
      最近更新 更多