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

Nest.js项目service注入TypeORM仓库后启动编译卡住是什么原因

问题根本原因

你在AutoService中通过@InjectRepository(Car)注入Car实体对应的Repository时,Nest的依赖注入容器需要你在所属的AutoModule中提前注册该实体对应的Repository提供者,你当前的automobile.module.ts缺少这一步配置,导致依赖解析卡住,启动过程中断没有报错输出。
另外你贴出的AutoService类代码上方漏加了@Injectable()装饰器,这也是Nest识别类为可注入Provider的必要条件,也可能引发依赖注入异常。

具体修复步骤

  1. 修改automobile.module.ts,导入TypeOrmModule并注册Car实体:
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { Car } from './entities/car.entity';
import { AutoService } from './automobile.service';
import { AutoController } from './automobile.controller';

@Module({
  // 新增该行,注册Car实体的Repository到当前模块的依赖注入容器
  imports: [TypeOrmModule.forFeature([Car])],
  controllers: [AutoController],
  providers: [AutoService],
})
export class AutoModule {}
  1. 补全automobile.service.ts的@Injectable()装饰器,代码示例如下:
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Car } from './entities/car.entity';
import { Repository } from 'typeorm';

import { CreateAutoDto } from './dto/create-auto.dto';
import { UpdateAutoDto } from './dto/update-auto.dto';

// 必须添加该装饰器,Nest才能识别该类为可注入的Provider
@Injectable()
export class AutoService {
  constructor(
    @InjectRepository(Car)
    private autoRepository:Repository<Car>,
  ){}

  create(createAutoDto: CreateAutoDto) {
    return this.autoRepository.save(createAutoDto)
  }
}

删除构造函数就能正常启动的原因

删除构造函数后,AutoService没有额外的外部依赖需要注入,Nest不需要解析Repository<Car>这个未注册的依赖,所以启动流程可以正常走完。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 18:42:01