How to inject a repository with typedi and typeorm

1.5k Views Asked by At

Im using typeorm, typedi and typegraphql (not nest.js) and am trying to inject my typeorm repository into the the service but its not working

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

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

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

The error im getting is

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."

even though I can print out the repository with Container.get(UserRepository)

Does anyone know what im doing wrong?

3

There are 3 best solutions below

0
On

In the service constructor, you need to bind the related functions. Usually, we see that the functions associated with the Service class may loose "this" so we need to make sure "this" is not lost. Either make the function(=>) or bind the function in constructor. Hope this helps.

3
On

try adding this annotation to your injected repo

import { InjectRepository } from 'typeorm-typedi-extensions';

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

you may need to install the typeorm-typedi-extensions package

and make sure you have useContainer(Container); in your bootstrapping process to register the typeorm container which should be the container from the above package

3
On

This was the solution:

  1. Add the container to the buildSchema function that apollo gives us:
  await dataSource.initialize();
  const schema = await buildSchema({
    resolvers,
    emitSchemaFile: true,
    container: Container,
  });
  1. Set the repositories on bootstrapping the app:
export const UserRepository = dataSource.getRepository(UserEntity).extend({});

Container.set("UserRepository", UserRepository);

  1. Use it in your service:
export class UserService {
  constructor(
    @Inject("UserRepository") private userRepository: Repository<UserEntity>
  ) {}
}