我遇到了这个问题:
[ERROR] 14:07:18 Error: Cannot inject the dependency at position #0 of "ListInterviewPagesUseCase" constructor. Reason: TypeInfo not known for "InterviewPagesRepository"
容器
import { container } from "tsyringe";
import { InterviewPagesRepository } from "../../modules/interview/repositories/implementations/InterviewPagesRepository";
import "./providers";
container.registerSingleton(
"InterviewPagesRepository",
InterviewPagesRepository
);
控制器
import { Request, Response } from "express";
import { container } from "tsyringe";
import { ListInterviewPagesUseCase } from "./ListInterviewPagesUseCase";
class ListInterviewPagesController {
async handle(request: Request, response: Response): Promise<Response> {
const listInterviewPagesUseCase = container.resolve(
ListInterviewPagesUseCase
);
const interviewPages = await listInterviewPagesUseCase.execute();
return response.json(interviewPages);
}
}
export { ListInterviewPagesController };
用例
import { inject, injectable } from "tsyringe";
import { InterviewPage } from "../../entities/InterviewPage";
import { IInterviewPagesRepository } from "../../repositories/IInterviewPagesRepository";
@injectable()
class ListInterviewPagesUseCase {
constructor(
@inject("InterviewPagesRepository")
private interviewPagesRepository: IInterviewPagesRepository
) {}
async execute(): Promise<InterviewPage[]> {
const interviewPages = await this.interviewPagesRepository.all();
return interviewPages;
}
}
export { ListInterviewPagesUseCase };
它在windows上正常工作,但现在我换成了mac并停止了工作。我已经从tsrynge
中放入了delay
,但仍然不起作用。
当我调用一个使用此存储库的路由时,就会发生这种情况,但看起来不错,数据库已经创建。
我的导入应用程序文件:
import "reflect-metadata";
import "dotenv/config";
import "./database";
import "./shared/container";
import cors from "cors";
import express from "express";
import swaggerUi from "swagger-ui-express";
import { router } from "./routes";
import swaggerFile from "./swagger.json";
考虑用@singleton
装饰InterviewPagesRepository
,而不是自己调用container.registerSingleton
:
import { singleton } from "tsyringe";
@singleton()
class InterviewPagesRepository {
@singleton
装饰器确实像您一样在内部调用registerSingleton()
,但它也存储它以用于其他构造函数的参数(请参见1→2,然后是3→4.→5( 。