导入 json 值时缺少 @Injectable 注释

Missing @Injectable annotation when importing json value

我目前正在尝试将 json 文件注入到我正在构建的服务中。 class 通过构造函数中的 @inject() 标记注入 json。 您可以在下面找到我正在使用的代码。

DiContainer.ts

import { Container, decorate, injectable } from "inversify";
import { IResponseBuilder, InjectionTypes, IUserIdGenerator, ILogger, IResponseRepository, IResponseService, IContextService, IFileWriter, IBoardSessionService, IIntent } from "./src/common/types";
import GoogleResponseBuilder from "./src/common/builders/googleResponseBuilder";
import UserIdGenerator from "./src/common/helpers/userIdGenerator";
import { DialogflowConversation } from "actions-on-google";
import WinstonLogger from "./src/common/winstonLogger";
import FileWriter from "./src/common/helpers/fileWriter";
import TextResponseRepository from "./src/repositories/textResponseRepository";
import SsmlResponseRepository from "./src/repositories/ssmlResponseRepository";
import ResponseSerivce from "./src/services/responseService";
import ContextService from "./src/services/contextService";
import { BoardService } from "./src/services/boardService";
import { BoardSessionService } from "./src/services/boardSessionService";
import WelcomeIntent from "./src/intents/new/welcomeIntent";
import uuid from "uuid/v4";

const sessionJson = require("./src/data/boardSessions.json");



const DIContainer = new Container();

DIContainer.bind<IResponseBuilder<DialogflowConversation>>(InjectionTypes.GoogleResponseBuilder).to(GoogleResponseBuilder);
DIContainer.bind<ILogger>(InjectionTypes.WinstonLogger).to(WinstonLogger);
DIContainer.bind<IFileWriter>(InjectionTypes.FileWriter).to(FileWriter);
DIContainer.bind<IUserIdGenerator>(InjectionTypes.UserIdGenerator).to(UserIdGenerator);

DIContainer.bind<IIntent>(InjectionTypes.WelcomeIntent).to(WelcomeIntent);

DIContainer.bind<IResponseRepository>(InjectionTypes.TextResponseRepository).to(TextResponseRepository);
DIContainer.bind<IResponseRepository>(InjectionTypes.SsmlResponseRepository).to(SsmlResponseRepository);
DIContainer.bind<IResponseService>(InjectionTypes.ResponseService).to(ResponseSerivce);
DIContainer.bind<IBoardSessionService>(InjectionTypes.BoardSessionService).to(BoardSessionService);
DIContainer.bind<IContextService>(InjectionTypes.ContextService).to(ContextService);

DIContainer.bind(InjectionTypes.SessionJSON).to(sessionJson);
DIContainer.bind(InjectionTypes.UUIDv4).toFunction(uuid);


export default DIContainer;

您尝试通过@inject 注入的每个依赖项都必须用@injectable 标记并通过绑定注册。 我真的不知道 decorate 函数是如何工作的(所以我不知道你是否可以用它来标记一个函数,而不是 class,作为可注入的)。

顺便说一句,我认为您只需将依赖项注册为动态值并返回所需函数即可实现您想要的效果,如 here 所述。在你的情况下,是这样的:

DIContainer.bind(InjectionTypes.UUIDv4).toDynamicValue((context: interfaces.Context) => { return uuid });

或者,您可以直接在您的服务中导入该函数而不注入它,或者将该函数包装在您可以标记为可注入的另一个服务中(比方说,一个 uuid 提供程序服务)。