[英]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;我正在尝试学习依赖注入并在一个项目中实现它大约一个星期,已经将 tsyringe 与 mongoose 一起使用,并且一切正常,但是由于某种原因,当我尝试将它与 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;我知道注入失败的原因是没有找到默认连接,但是在mt其他mongoose项目中没有必要设置这个tsyringe连接;
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:这是控制器代码、模型代码和路由代码,我隐藏了 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
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:问题是我在完全连接到数据库之前实例化了控制器,我发现的解决方案是使用 tsyringe 的延迟装饰器,并取出私有属性,控制器类保持如下:
constructor(@inject(delay(() => TeamService)) public TeamService: TeamService) {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.