繁体   English   中英

尝试使用 tsyringe 和 typeorm 进行依赖注入时遇到问题

[英]Having problems trying dependency injection with tsyringe and typeorm

我正在尝试学习依赖注入并在一个项目中实现它大约一个星期,已经将 tsyringe 与 mongoose 一起使用,并且一切正常,但是由于某种原因,当我尝试将它与 typeorm 一起使用时;

我知道注入失败的原因是没有找到默认连接,但是在mt其他mongoose项目中没有必要设置这个tsyringe连接;

这是控制器代码、模型代码和路由代码,我隐藏了 create 方法,因为我知道问题不存在,因为我已经对其进行了很多次测试,任何提示或建议都会有所帮助,但可能是不在 ormconfig.json 中,但我还是会放它,因为我不确定:

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

问题是我在完全连接到数据库之前实例化了控制器,我发现的解决方案是使用 tsyringe 的延迟装饰器,并取出私有属性,控制器类保持如下:

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

暂无
暂无

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

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