inversify for TypeScript: 完整指南及示例

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

什么是 Inversify 以及为什么需要它?

\n\n

Inversify 是一个强大且轻量级的 IoC(控制反转)容器,适用于 TypeScript 和 JavaScript。它实现了依赖注入(DI)模式,这是 SOLID 原则中的关键原则之一。Inversify 允许管理类之间的依赖关系,使代码更加模块化、可测试和可维护。

\n\n

为什么需要它? 在传统编程中,类自己创建其依赖关系(例如,通过 new)。这会导致代码高度耦合。Inversify 反转了这一过程:依赖关系从外部“注入”(因此得名——控制反转)。容器负责创建和管理对象的生命周期。

\n\n

使用 Inversify 的主要优势:

\n
    \n
  • 低耦合: 类依赖于抽象(接口),而不是具体实现。
  • \n
  • 易于测试: 您可以轻松地在测试中将真实依赖替换为模拟/桩对象。
  • \n
  • 生命周期管理: 容器可以创建单例对象,也可以每次都创建新实例。
  • \n
  • 可读性和可维护性: 所有依赖关系都明确声明,易于追踪。
  • \n
  • 可扩展性: 非常适合具有多个模块的大型项目。
  • \n
\n\n

安装 Inversify

\n\n

Inversify 通过 npm 安装。为了与 TypeScript 一起使用,还需要安装 reflect-metadata(用于处理装饰器的库)并配置 tsconfig.json。

\n\n
# 安装 Inversify 和 reflect-metadata\nnpm install inversify reflect-metadata --save\n\n# 安装 TypeScript 的类型(如果未安装)\nnpm install @types/node --save-dev\n
\n\n

配置 tsconfig.json:

\n
{\n  "compilerOptions": {\n    "target": "ES6",\n    "module": "commonjs",\n    "experimentalDecorators": true,\n    "emitDecoratorMetadata": true,\n    "strict": true,\n    "esModuleInterop": true,\n    "skipLibCheck": true,\n    "forceConsistentCasingInFileNames": true,\n    "outDir": "./dist",\n    "rootDir": "./src",\n    "types": ["reflect-metadata"]\n  },\n  "include": ["src/**/*"],\n  "exclude": ["node_modules", "dist"]\n}\n
\n\n

重要提示: 装饰器 @injectable() 和 @inject() 仅在启用 experimentalDecorators 和 emitDecoratorMetadata 时有效。

\n\n

快速入门及代码示例

\n\n

让我们创建一个简单的示例:一个用于发送通知的服务。我们将有一个接口 INotificationService,它的实现 EmailNotificationService,以及一个使用该服务的类 UserService。

\n\n
// 1. 导入必要的模块\nimport "reflect-metadata";\nimport { Container, injectable, inject } from "inversify";\n\n// 2. 定义接口(抽象)\ninterface INotificationService {\n  send(message: string): void;\n}\n\n// 3. 接口的实现\n@injectable()\nclass EmailNotificationService implements INotificationService {\n  send(message: string): void {\n    console.log(`发送邮件: ${message}`);\n  }\n}\n\n// 4. 依赖于 INotificationService 的类\n@injectable()\nclass UserService {\n  private notificationService: INotificationService;\n\n  constructor(\n    @inject("INotificationService") notificationService: INotificationService\n  ) {\n    this.notificationService = notificationService;\n  }\n\n  notifyUser(userId: string): void {\n    this.notificationService.send(`用户 ${userId} 的通知`);\n  }\n}\n\n// 5. 创建容器并注册依赖关系\nconst container = new Container();\ncontainer.bind
                
    
    

推荐