首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用typedi和typeorm注入存储库

如何使用typedi和typeorm注入存储库
EN

Stack Overflow用户
提问于 2022-10-02 18:18:27
回答 2查看 123关注 0票数 0

我正在使用typeorm、typedi和typegraphql (不是nest.js),并试图将我的typeorm存储库注入服务,但它无法工作。

代码语言:javascript
复制
Container.set("UserRepository", dataSource.getRepository(UserEntity));

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

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

我得到的错误是

代码语言:javascript
复制
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)打印出存储库

有人知道我做错了什么吗?

EN

回答 2

Stack Overflow用户

发布于 2022-11-07 14:41:35

尝试将此注释添加到注入的回购中。

代码语言:javascript
复制
import { InjectRepository } from 'typeorm-typedi-extensions';

constructor(@InjectRepository() private userRepository: Repository<UserEntity>) {}

您可能需要安装typeorm-typedi扩展包

并确保在引导过程中有useContainer(Container);来注册typeorm容器,该容器应该是上述包中的容器。

票数 0
EN

Stack Overflow用户

发布于 2022-11-08 16:54:43

这就是解决办法:

  1. 将容器添加到阿波罗给我们的buildSchema函数中:
代码语言:javascript
复制
  await dataSource.initialize();
  const schema = await buildSchema({
    resolvers,
    emitSchemaFile: true,
    container: Container,
  });
  1. 在引导应用程序时设置存储库:
代码语言:javascript
复制
export const UserRepository = dataSource.getRepository(UserEntity).extend({});

Container.set("UserRepository", UserRepository);
  1. 在你的服务中使用它:
代码语言:javascript
复制
export class UserService {
  constructor(
    @Inject("UserRepository") private userRepository: Repository<UserEntity>
  ) {}
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73928282

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档