typeorm-typedi-extensions: injected repository is always undefined

Hi I’m trying to inject some repository into a routing-controllers controller like this:

import { Param, Body, Get, Post, Put, Delete, JsonController } from "routing-controllers";
import { InjectRepository } from "typeorm-typedi-extensions";
import { Repository } from "typeorm";
import { User } from "../entities/User";
import { Service } from "typedi";

@JsonController('/users')
@Service()
export class UserController {

    @InjectRepository(User)
    private repository: Repository<User>;

    @Get("/")
    getAll() {
        return this.repository.find();
    }
}

but this.repository is always undefined!

this is my app entry main.ts file:

import "reflect-metadata";
import { createConnection, useContainer} from 'typeorm';
import { createExpressServer } from "routing-controllers";
import { UserController } from "./src/controllers/UserController";

import { Container } from 'typedi';

useContainer(Container);
createConnection().then(async connection => {
}).catch(error => console.log(error));

const app = createExpressServer({
    controllers: [UserController] // we specify controllers we want to use
 });
 app.listen(3000);

all entities are created and express is working.

About this issue

  • Original URL
  • State: closed
  • Created 6 years ago
  • Reactions: 10
  • Comments: 20 (1 by maintainers)

Most upvoted comments

For me, using type-grapghql the difference was in

const schema = await buildSchema({
    resolvers: [UserResolver],
    // need to register the container here as well
    container: Container
})

just using useContainer(Container) from typeorm is not enough

So my solution was to replace this

export class UserService {
    constructor(
         @InjectRepository(UserRepository)
         private userRepository: UserRepository;

         @InjectRepository(AuthRepository)
         private authRepository: AuthRepository;
     ) {  }
}

with this using Connection from typeorm

export class UserService {
    private userRepository: UserRepository;
    private authRepository: AuthRepository;
    constructor(
        private readonly connection: Connection
    ) {
        this.userRepository = this.connection.getCustomRepository(UserRepository);
        this.authRepository = this.connection.getCustomRepository(AuthRepository);
    }
}

Now it work like charm 😃

@feimosi I found the source of the issue. I am trying to inject repository into repository. And for some reason this is not working. When I try to inject the same repository into service - it does work.