You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

非Nest.js环境下TypeDI+TypeORM注入Repository失败求助

问题

在非Nest.js环境下使用TypeORM、TypeDI和TypeGraphQL时,尝试将TypeORM Repository注入到服务中失败。

代码示例:

Container.set("UserRepository", dataSource.getRepository(UserEntity));

@Service()
export class UserService {
  constructor(private userRepository: Repository<UserEntity>) {}

  async createUser({
    name,
    email,
    password,
  }: Input {...}

错误信息:

Service with "MaybeConstructable<Repository>" identifier was not found in the container. Register it before usage via explicitly calling the "Container.set" function or using the "@Service()" decorator.

即便能通过Container.get(UserRepository)获取到Repository,问题依然存在。

解决方案

问题核心是注册时用了字符串标识符"UserRepository",但注入时依赖的是Repository<UserEntity>类型,TypeDI默认以类型作为服务标识符,两者不匹配导致找不到对应服务。

有两种解决方式:

  • 用类型作为标识符注册
    直接将Repository<UserEntity>类型作为注册键,和注入时的类型保持一致:

    Container.set(Repository<UserEntity>, dataSource.getRepository(UserEntity));
    

    这样构造函数里的类型注入就能自动匹配到对应的Repository实例。

  • 结合@Inject()装饰器指定字符串标识符
    保留原有的字符串注册方式,在构造函数参数上通过@Inject()明确指定要注入的服务标识符:

    import { Inject } from "typedi";
    
    @Service()
    export class UserService {
      constructor(@Inject("UserRepository") private userRepository: Repository<UserEntity>) {}
      // 后续业务逻辑...
    }
    

如果你的UserRepository是自定义的Repository类(而非直接使用TypeORM的泛型Repository),则注册时要以该类作为标识符:

Container.set(UserRepository, dataSource.getRepository(UserEntity));

注入时同样可以直接用类作为类型,或者结合@Inject(UserRepository)指定。

内容的提问来源于stack exchange,提问作者Sid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 00:40:28