ReactNative进阶(三十一): IoC 框架 InversifyJS解读

朱雀 2022-10-14 10:49 382阅读 0赞

文章目录

    • 一、简介
    • 二、为什么要有 InversifyJS ?
    • 三、目标
    • 四、安装
    • 五、应用示例
      • 步骤 1: 声明接口和类型
      • 步骤 2: 使用 @injectable 和 @inject 装饰器声明依赖
      • 步骤 3: 创建和配置容器
      • 步骤 4: 解析依赖
    • 六、拓展阅读

在这里插入图片描述

一、简介

InversifyJS ,一个强大又轻量的控制反转容器,提供给JavaScriptNode.js 应用使用,使用TypeScript编写。

InversifyJS 是一个轻量的 (4KB) 控制反转容器 (IoC),可用于编写 TypeScriptJavaScript 应用。 它使用类构造函数去定义和注入它的依赖。InversifyJS API 友好易懂, 鼓励对 OOPIoC 最佳实践的应用.

二、为什么要有 InversifyJS ?

JavaScript 现在支持面向对象编程,基于类的继承。 这些特性不错但事实上它们也是危险的。 我们需要一个优秀的面向对象设计(比如 SOLID),Composite Reuse等)来保护我们避免这些威胁。然而,面向对象的设计是复杂的,所以InversifyJS应运而生。

InversifyJS 是一个工具,它能帮助 JavaScript 开发者,写出出色的面向对象设计的代码。

三、目标

InversifyJS有4个主要目标:

  • 允许JavaScript开发人员编写遵循 SOLID 原则的代码。
  • 促进并鼓励遵守最佳的面向对象编程(OOP)和依赖注入(IoC)实践。
  • 尽可能少的运行时开销。
  • 提供艺术编程体验和生态。

四、安装

可以使用npm获得最新的版本和类型定义:

  1. $ npm install inversify reflect-metadata --save

注:由于 InversifyJS 通过反射来获取装饰器的相关元数据,所以需要额外安装库 reflect-metadata

Inversify npm 包已经包含了 InversifyJS 的类型定义。

:警示: 重要! InversifyJS 需要 TypeScript 的版本 >= 2.0 还有experimentalDecorators, emitDecoratorMetadata, types and lib 在 tsconfig.json 中 compilerOptions 的配置如下:

  1. {
  2. "compilerOptions": {
  3. "target": "es5",
  4. "lib": ["es6"],
  5. "types": ["reflect-metadata"],
  6. "module": "commonjs",
  7. "moduleResolution": "node",
  8. "experimentalDecorators": true,
  9. "emitDecoratorMetadata": true
  10. }
  11. }

inversifyjs需要现代JavaScript引擎,支持以下特性:

  • Reflect metadata
  • Map
  • Promise (Only required if using provider injection)
  • Proxy (Only required if using activation handlers)

如果运行环境不支持这些特性,可能需要导入 shimpolyfill.

:警示: reflect-metadata polyfill 应该在您整个应用中只导入一次, 因为 Reflect 对象需要成为一个全局的单例。

五、应用示例

inversifyjs 基本用法和 API应用示例如下:

步骤 1: 声明接口和类型

目标是编写遵循依赖倒置原则的代码。

这意味着我们应该 ”依赖于抽象而不依赖于具体实现“ 。

先声明一些接口(抽象)。

  1. // file interfaces.ts
  2. interface Warrior {
  3. fight(): string;
  4. sneak(): string;
  5. }
  6. interface Weapon {
  7. hit(): string;
  8. }
  9. interface ThrowableWeapon {
  10. throw(): string;
  11. }

Inversifyjs 需要在运行时使用类型标记作为标识符。接下来将使用 Symbol 作为标识符,也可以使用类或字符串。

  1. // file types.ts
  2. const TYPES = {
  3. Warrior: Symbol.for("Warrior"),
  4. Weapon: Symbol.for("Weapon"),
  5. ThrowableWeapon: Symbol.for("ThrowableWeapon")
  6. };
  7. export { TYPES };

警示: 推荐使用 Symbol,但 InversifyJS 也支持使用类和字符串字面值。

步骤 2: 使用 @injectable 和 @inject 装饰器声明依赖

接下来,声明一些类,实现刚刚声明的接口。需要使用 @injectable 装饰器去注解。

当一个类依赖于某个接口时,我们需要使用 @inject 装饰器,来定义在运行时可用的接口标识。在这种情况下,将使用 Symbol, 如 Symbol.for("Weapon")Symbol.for("ThrowableWeapon") 作为运行时的标识。

  1. // file entities.ts
  2. import { injectable, inject } from "inversify";
  3. import "reflect-metadata";
  4. import { Weapon, ThrowableWeapon, Warrior } from "./interfaces"
  5. import { TYPES } from "./types";
  6. @injectable()
  7. class Katana implements Weapon {
  8. public hit() {
  9. return "cut!";
  10. }
  11. }
  12. @injectable()
  13. class Shuriken implements ThrowableWeapon {
  14. public throw() {
  15. return "hit!";
  16. }
  17. }
  18. @injectable()
  19. class Ninja implements Warrior {
  20. private _katana: Weapon;
  21. private _shuriken: ThrowableWeapon;
  22. public constructor(
  23. @inject(TYPES.Weapon) katana: Weapon,
  24. @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
  25. ) {
  26. this._katana = katana;
  27. this._shuriken = shuriken;
  28. }
  29. public fight() { return this._katana.hit(); }
  30. public sneak() { return this._shuriken.throw(); }
  31. }
  32. export { Ninja, Katana, Shuriken };

如果更喜欢使用属性注入而不是构造函数注入,那就可以不用声明类的构造函数了,属性注入方式如下:

  1. @injectable()
  2. class Ninja implements Warrior {
  3. @inject(TYPES.Weapon) private _katana: Weapon;
  4. @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
  5. public fight() { return this._katana.hit(); }
  6. public sneak() { return this._shuriken.throw(); }
  7. }

步骤 3: 创建和配置容器

推荐在命名为 inversify.config.ts 的文件中创建和配置容器。这是唯一有耦合的地方。 在项目其余部分中的类,不应该包含对其他类的引用。

  1. // file inversify.config.ts
  2. import { Container } from "inversify";
  3. import { TYPES } from "./types";
  4. import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
  5. import { Ninja, Katana, Shuriken } from "./entities";
  6. const myContainer = new Container();
  7. myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
  8. myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
  9. myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);
  10. export { myContainer };

步骤 4: 解析依赖

可以使用方法 get<T>Container 中获得依赖。记得应该在项目根结构(尽可能靠近应用程序的入口点的位置)去解析依赖,避免服务器定位反模式。

  1. import { myContainer } from "./inversify.config";
  2. import { TYPES } from "./types";
  3. import { Warrior } from "./interfaces";
  4. const ninja = myContainer.get<Warrior>(TYPES.Warrior);
  5. expect(ninja.fight()).eql("cut!"); // true
  6. expect(ninja.sneak()).eql("hit!"); // true

正如我们所看到的,Katana and Shuriken 被成功的解析和注入进 Ninja。

InversifyJS 支持 ES5ES6 ,而且可以在没有 TypeScript 环境下使用。

不做知识的搬运工,只做知识的汇聚者!

注:本文节选自https://doc.inversify.cloud/zh_cn/,学习InversifyJS,看此文足矣!!墙裂推荐!!

六、拓展阅读

  • InversifyJS【Github】
  • 中文文档

发表评论

表情:
评论列表 (有 0 条评论,382人围观)

还没有评论,来说两句吧...

相关阅读