简体   繁体   English

如何将存储库提供程序注入 Nestjs 中的实体(不是 TypeORM)

[英]How to inject repository providers into an entity in Nestjs (not TypeORM)

How could a repository provider be injected in a plain entity class in NestJS?如何将存储库提供程序注入 NestJS 中的普通实体 class 中?

In the following code, this.customerRepository is not injected by NestJS, is undefined.在下面的代码中, this.customerRepository不是由 NestJS 注入的,是未定义的。

export class UserAggregateEntity  {
  
  @Inject()
  public customerRepository: CustomerRepository;

  private customer: CustomerEntity;

  constructor(private user: UserEntity) {}

  async createCustomer(customer: CustomerEntity): Promise<string> {
    customer.user = this.root.id;

    // here error Cannot read property 'create' of undefined
    const savedCustomer = await this.customerRepository.create(customer); 
    this.customer = savedCustomer;

    return customer.id;
  }
}

UserAggregateEntity class is called by something like... UserAggregateEntity class 被类似...

const userAggregate = new UserAggregateEntity(user);
await userAggregate.createCustomer(customer);

CustomerRepository cannot be instantiated in the createCustomer method because it has to be injected with a DAO and other providers. CustomerRepository 不能在createCustomer方法中实例化,因为它必须注入 DAO 和其他提供程序。
CustomerRepository is @Injectable(), defined as provider in the module, and used elsewhere successfully. CustomerRepository 是@Injectable(),在模块中定义为提供者,并在其他地方成功使用。

Thanks谢谢

If you are calling new WhateverClass() yourself, then you are in charge of whatever that class may need to function.如果您自己调用 newwhateverClass new WhateverClass() ,那么您负责 class 到 function 可能需要的任何内容。 Nest will do absolutely no injection on classes that you manage creating yourself, nor should it. Nest 绝对不会对您自己创建的类进行注入,也不应该这样做。 There's no hooks set up for watching for the creation of the class or modification of the constructor prototype, all of the metadata nd decorators we use are just there so that Nest can read the metadata and know how to create the class when you ask Nest to.没有设置挂钩来监视 class 的创建或构造函数原型的修改,我们使用的所有元数据和装饰器都在那里,以便 Nest 可以读取元数据并知道如何在您要求 Nest 时创建 class . Calling new bypasses that entire system.调用new会绕过整个系统。 So you'll need to call new UserAggregateEntity() and have some sort of setter for the customerRepository property that you pass the repository to.因此,您需要调用new UserAggregateEntity()并为您将存储库传递到的customerRepository属性设置某种设置器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM