Search code examples
typescriptexpresstypeorm

Having problems trying dependency injection with tsyringe and typeorm


I am trying to learn dependency injection and implement it in one project for about a week now, already used tsyringe with mongoose, and it went ok, but for some reason when i try using it with typeorm;

I recieve that the reason why the injection failed is because no default connection was found, but there was no need to setup this tsyringe connection in mt other mongoose projects;

Here is the controller code, the model code, and the routes code, i hide the create method because i know the problem is not there because i already tested it a lot of times, any tipo or suggestion will be helpful, and probably but is not in ormconfig.json but i will put it anyway because i am not sure:

import { Request, Response } from "express"
import { autoInjectable } from "tsyringe";
import { Repository } from "typeorm";
import {TeamEntity} from "../models/team.model";

@autoInjectable()
export default class TeamController {
    private repo: Repository<any>

    constructor(repo?: TeamEntity) {
        this.repo = repo.repo;
    }

    create = async (req: Request, res: Response) =>{
    // creates a new team
}
}

// team.controller.ts

@Entity({name: "teams"})
export default class TeamModel extends BaseEntity implements TeamI{
    @PrimaryGeneratedColumn({name: "team_id"})
    teamId: number

    @Column({name: "team_name"})
    teamName: string

}

@singleton()
export class TeamEntity{
    entity: BaseEntity = new TeamModel();
    repo: Repository<any> = getRepository(TeamModel)
}

//team.model.ts

import { Router } from "express";
import TeamController from "./controllers/team.controller";

const teamController = new TeamController();

const appRouter = Router();

appRouter.post("/teams", () => teamController.create);

export default appRouter;

//routes.ts
{
    "type": "postgres",
    "database": "postgres",
    "password": "<password>",
    "logging": true,
    "entities": [
       "src/models/*.model.ts"
    ],
    "migrations": [
       "src/migrations/*.migration.ts"
    ],
    "cli": {
       "entitiesDir": "src/models/",
       "migrationsDir": "src/migrations/"
    }
 }

\\ ormconfig.json

Solution

  • The problem was that i was instanciating the Controller before fully connceting to the database, the solution i found was to use delay decorator of tsyringe, and take out the private attribute, the controller class stayed like this:

        constructor(@inject(delay(() => TeamService)) public TeamService: TeamService) {
        }