这个UserRepository为什么不需要@Injectable()装饰器

来源:12-4 抽象公共Repository:解决多数据库请求响应

tyler4400

2025-08-06

这个类应该被@injectable装饰吧, 这样才能被nest DI容器管理和注入到controller中

https://img1.sycdn.imooc.com/szimg/09f7226809931f2924301538.jpg


另外, controller是单例的, 在class内部定义了一个私有属性,会影响到别的请求的, 这样并发请求就会污染混乱吧

https://img1.sycdn.imooc.com/szimg/f0b1e26809944a5213561454.jpg

写回答

1回答

Brian

2025-08-10

这个类应该被@injectable装饰吧, 这样才能被nest DI容器管理和注入到controller中

——https://git.imooc.com/coding-905/nestjs-starter/src/main/src/user/user.module.ts#L59 如果在providers里面添加了,作用是一样。


 controller是单例的, 在class内部定义了一个私有属性,会影响到别的请求的, 这样并发请求就会污染混乱吧——上面这个是示例应用,可以把 UserRepository 设为 request-scoped。还可以,在 controller 里用 @Req() 取到请求对象,类似下面的代码:

@Controller()
export class AppController {
  constructor(private readonly userRepoHelper: UserRepoHelper) {} // 名字随意

  @Get()
  async getHello(@Req() req: Request) {
    const repo = this.userRepoHelper.getRepository(req); // 每次请求都重新判断
    return repo.find();
  }
}

然后这个UserRepoHelper如下(伪代码):

@Injectable()
export class UserRepoHelper {
  constructor(
    @InjectRepository(User) private readonly repoDefault: Repository<User>,
    @InjectRepository(User, 'mysql1') private readonly repoTenant1: Repository<User>,
  ) {}

  getRepository(req: Request): Repository<User> {
    const tenantId = String(req.headers['x-tenant-id'] ?? '');
    return tenantId === '1' ? this.repoTenant1 : this.repoDefault;
  }
}


0
0

NestJS 从拔高到精通,大型复杂业务架构落地实践

NestJS 从拔高到精通,大型复杂业务架构落地实践

153 学习 · 43 问题

查看课程