# @gritcode/inversify 中文文档

规范地址：https://npmcn.com/package/%40gritcode/inversify/

版本：6\.0\.2
npm 元数据更新时间：2024-05-30T06:19:11.335Z
中文译文更新时间：2026-11-17T05:03:48.982Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gritcode/inversify
原文对照：https://npmcn.com/package/%40gritcode/inversify/?lang=original
项目主页：http://inversify.io/
源码仓库：https://github.com/inversify/InversifyJS

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：1.5 MB，273 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：0 个
- 首次发布：2024-05-30T06:19:10.781Z
- 最新版本发布：2024-05-30T06:19:11.056Z
- 近 30 天下载量：6329（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：1（近 12 个月 0 个）

## 中文简介

JavaScript和Node.js应用程序由TypeScript提供动力的强大的轻量级反转控制容器.

## 安装

```sh
npm install @gritcode/inversify
```

也可以使用：`pnpm add @gritcode/inversify`、`yarn add @gritcode/inversify`、`bun add @gritcode/inversify`

## README

![](https://raw.githubusercontent.com/inversify/inversify.github.io/master/img/cover.jpg)

[![NPM version](https://img.shields.io/npm/v/inversify?color=0476bc&label=)](https://www.npmjs.com/package/inversify) [![NPM Downloads](https://img.shields.io/npm/dm/inversify?color=3890aa&label=)](https://www.npmjs.com/package/inversify) [![Docs](https://img.shields.io/static/v1?label=&message=docs&color=1e8a7a)](https://github.com/inversify/InversifyJS#-the-inversifyjs-features-and-api) [![Codecov](https://codecov.io/gh/inversify/InversifyJS/branch/master/graph/badge.svg?token=KfAKzuGs01)](https://codecov.io/gh/inversify/InversifyJS)  
  
[![GitHub stars](https://img.shields.io/github/stars/inversify/InversifyJS?style=social)](https://github.com/inversify/InversifyJS) [![Discord Server](https://img.shields.io/discord/816766547879657532?style=social&logo=discord)](https://discord.gg/jXcMagAPnm)

# 废除JS

JavaScript & Node.js 应用软件由TypeScript提供动力的强大的轻量级反转控制容器.

## 关于

倒置JS是TypeScript和JavaScript应用的轻量级倒置控制(IoC)容器. 一个IoC容器使用分级构造器来识别并注入其依赖性. VersifyJS有一个友好的API,并鼓励使用最佳OOP和IoC做法.

## 动机

JavaScript 现在支持面向对象(OO)的编程,具有基于类的继承. 这些特征是伟大的,但事实是,它们也是 [危险](https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4)。 。 。 .

我们需要一个良好的OO设计([安静](https://en.wikipedia.org/wiki/SOLID_\(object-oriented_design\)), (中文(简体) ), [复合再使用](https://en.wikipedia.org/wiki/Composition_over_inheritance)保护自己免受这些威胁。 问题是OO设计很困难,这正是我们创建InversifyJS的原因.

VersifyJS是帮助JavaScript开发者以良好的OO设计写出代码的工具.

## 哲学

已经制定了四个主要目标:

1.  允许JavaScript开发者编写符合SOLID原则的代码.
    
2.  便利和鼓励遵守《业务业务方案》和《信息通报》的最佳做法.
    
3.  尽可能少增加运行时间 .
    
4.  提供a [最新发展经验](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md)。 。 。 .
    

## 证词

**[内特·科哈里](https://twitter.com/nkohari)** - 作者: [输入](https://github.com/ninject/Ninject)

> _"干得不错! 我在为JavaScript和TypeScript创建DI框架方面拍了几张照片,但缺乏RTTI确实阻碍了事情的发展._ _ES7元数据让我们成为其中的一部分(如您所发现的). 继续伟大的工作!"_

**[米歇尔·威斯特斯特拉特](https://twitter.com/mweststrate)** - 作者: [移动X](https://github.com/mobxjs/mobx)

> _依赖性注射,如 InverfyJS 效果良好_

## 一些使用逆JS的公司

[![](https://avatars0.githubusercontent.com/u/6154722?s=200&v=4)](https://opensource.microsoft.com/)[![](https://avatars2.githubusercontent.com/u/69631?s=200&v=4)](https://code.facebook.com/projects/1021334114569758/nuclide/)[![](https://avatars0.githubusercontent.com/u/2232217?s=200&v=4)](https://aws.github.io/aws-amplify/)[![](https://avatars0.githubusercontent.com/u/1520648?s=200&v=4)](https://www.plainconcepts.com/)[![](https://avatars3.githubusercontent.com/u/6962987?s=200&v=4)](https://api.slack.com/)[![](https://pbs.twimg.com/profile_images/827249559046909954/SyaBPcH8_400x400.jpg)](http://acia.aon.com/index.php/home/) [![](https://avatars3.githubusercontent.com/u/114767?s=200&v=4)](https://www.lonelyplanet.com/) [![](https://avatars0.githubusercontent.com/u/25283328?s=200&v=4)](https://jincor.com/) [![](https://avatars1.githubusercontent.com/u/1957282?s=200&v=4)](https://www.web-computing.de/) [![](https://avatars1.githubusercontent.com/u/17648048?s=200&v=4)](https://dcos.io/) [![](https://avatars0.githubusercontent.com/u/16970371?s=200&v=4)](https://typefox.io/) [![](https://avatars0.githubusercontent.com/u/18010308?s=200&v=4)](https://code4.ro/) [![](https://user-images.githubusercontent.com/10656223/33888109-fae0852e-df43-11e7-97f6-9db543da0bde.png)](http://www.baidu.com/) [![](https://avatars2.githubusercontent.com/u/8085382?s=200&v=4)](https://www.imdada.cn/) [![](https://avatars2.githubusercontent.com/u/17041151?s=200&v=4)](https://www.ato.gov.au/) [![](https://avatars1.githubusercontent.com/u/14963540?s=200&v=4)](https://www.kaneoh.com/) [![](https://avatars0.githubusercontent.com/u/26021686?s=200&v=4)](https://particl.io/) [![](https://avatars2.githubusercontent.com/u/24523195?s=200&v=4)](https://slackmap.com/) [![](https://avatars3.githubusercontent.com/u/16556899?s=200&v=4)](https://www.go1.com/) [![](https://avatars3.githubusercontent.com/u/23475730?s=200&v=4)](http://www.stellwagengroup.com/stellwagen-technology/) [![](https://avatars1.githubusercontent.com/u/15262567?s=200&v=4)](https://www.edrlab.org/) [![](https://avatars1.githubusercontent.com/u/10072104?s=200&v=4)](https://www.goodgamestudios.com/) [![](https://avatars2.githubusercontent.com/u/13613760?s=200&v=4)](https://freshfox.at/) [![](https://avatars1.githubusercontent.com/u/864482?s=200&v=4)](https://schubergphilis.com/)

## \* 安装

您可以使用您首选的软件包管理器获取最新版本和类型定义 :

```sh
> npm install inversify reflect-metadata --save
> yarn add inversify reflect-metadata
> pnpm add inversify reflect-metadata
```

> ❕**闪电!** 如果您想要使用更安全的反射元数据类型, 请尝试 [`@abraham/reflection`](https://www.npmjs.com/package/@abraham/reflection)

VersifyJS类型定义包含在versify npm包中.

> : 警告: **重要的东西!** 校正JS 需要 TypeScript QQ 4.4 和 `experimentalDecorators`, (中文(简体) ), `emitDecoratorMetadata`, (中文(简体) ), `types` 财务报告和审定财务报表 `lib` 编辑选项 `tsconfig.json` 文档.

```json
{
    "compilerOptions": {
        "target": "es5",
        "lib": ["es6"],
        "types": ["reflect-metadata"],
        "module": "commonjs",
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true
    }
}
```

VersifyJS需要现代JavaScript引擎,支持:

-   [反映元数据](https://rbuckton.github.io/reflect-metadata/)
-   [地图](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)
-   [答应](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) (仅在使用时需要) [供应商注射](https://github.com/inversify/InversifyJS/blob/master/wiki/provider_injection.md)(中文(简体) )
-   [代理服务器](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) (仅在使用时需要) [激活处理器](https://github.com/inversify/InversifyJS/blob/master/wiki/activation_handler.md)(中文(简体) )

如果你的环境不支持其中之一,你将需要导入 shim 或多填充.

> : 警告: **这个 `reflect-metadata` 整个应用程序只导入一次多填充** 因为反射对象的意思是是一个全局单子. 详情请查看 [这里](https://github.com/inversify/InversifyJS/issues/262#issuecomment-227593844)。 。 。 .

看看这个 [环境支持和多填充](https://github.com/inversify/InversifyJS/blob/master/wiki/environment.md) 在维基百科和 [基本实例](https://github.com/inversify/inversify-basic-example) 学习更多.

## 基本情况

让我们看看用TypeScript来验证JS的基本用法和API:

### 步骤1: 宣布您的界面和类型

我们的目标是写出符合 [依赖倒置原则](https://en.wikipedia.org/wiki/Dependency_inversion_principle)。 。 。 . 这意味着我们应该"依赖于抽象,而不依赖于抽象". 我们先宣布一些接口(缩写).

```ts
// file interfaces.ts

export interface Warrior {
    fight(): string;
    sneak(): string;
}

export interface Weapon {
    hit(): string;
}

export interface ThrowableWeapon {
    throw(): string;
}
```

VersifyJS需要在运行时使用该类型作为标识符. 我们使用符号作为标识符,但您也可以使用类或字符串字节.

请确定将这个排行榜放入一个相册中(见bug #1455)

```ts
// file types.ts

const TYPES = {
    Warrior: Symbol.for("Warrior"),
    Weapon: Symbol.for("Weapon"),
    ThrowableWeapon: Symbol.for("ThrowableWeapon")
};

export { TYPES };

```

> **说明**:建议使用符号,但InversifyJS也支持类和字符串的用法(请参见特性部分以多学习).

### 步骤2:使用 `@injectable` 打开 `@inject` 装饰器

让我们继续宣布一些课程(合并). 这些课程是执行我们刚刚宣布的界面。 所有课程都必须加上 `@injectable` 装饰师.

当类依赖接口时,我们也需要使用 `@inject` 用于定义运行时可用的接口标识符的装饰器 。 这样的话,我们就用符号 `Symbol.for("Weapon")` 财务报告和审定财务报表 `Symbol.for("ThrowableWeapon")` 作为运行时间标识符.

```ts
// file entities.ts

import { injectable, inject } from "inversify";
import "reflect-metadata";
import { Weapon, ThrowableWeapon, Warrior } from "./interfaces";
import { TYPES } from "./types";

@injectable()
class Katana implements Weapon {
    public hit() {
        return "cut!";
    }
}

@injectable()
class Shuriken implements ThrowableWeapon {
    public throw() {
        return "hit!";
    }
}

@injectable()
class Ninja implements Warrior {

    private _katana: Weapon;
    private _shuriken: ThrowableWeapon;

    public constructor(
        @inject(TYPES.Weapon) katana: Weapon,
        @inject(TYPES.ThrowableWeapon) shuriken: ThrowableWeapon
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }

    public fight() { return this._katana.hit(); }
    public sneak() { return this._shuriken.throw(); }

}

export { Ninja, Katana, Shuriken };
```

如果你更喜欢的话,你可以使用属性注射而不是构造器注射,这样你就不必声明类构造器:

```ts
@injectable()
class Ninja implements Warrior {
    @inject(TYPES.Weapon) private _katana: Weapon;
    @inject(TYPES.ThrowableWeapon) private _shuriken: ThrowableWeapon;
    public fight() { return this._katana.hit(); }
    public sneak() { return this._shuriken.throw(); }
}
```

### 第3步:创建和配置容器

我们建议在一份名为 `inversify.config.ts`。这是唯一一个有 连接的地方. 其余的应用中,您的课程应该没有其他课程的参考.

```ts
// file inversify.config.ts

import { Container } from "inversify";
import { TYPES } from "./types";
import { Warrior, Weapon, ThrowableWeapon } from "./interfaces";
import { Ninja, Katana, Shuriken } from "./entities";

const myContainer = new Container();
myContainer.bind<Warrior>(TYPES.Warrior).to(Ninja);
myContainer.bind<Weapon>(TYPES.Weapon).to(Katana);
myContainer.bind<ThrowableWeapon>(TYPES.ThrowableWeapon).to(Shuriken);

export { myContainer };
```

### 步骤4:解决依赖关系

你可以用这种方法 `get<T>` 从 `Container` 类解决依赖. 记住,你应该只这样做 在你的 [组成根](http://blog.ploeh.dk/2011/07/28/CompositionRoot/) 以避开 [服务定位器反平板](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern/)。 。 。 .

```ts
import { myContainer } from "./inversify.config";
import { TYPES } from "./types";
import { Warrior } from "./interfaces";

const ninja = myContainer.get<Warrior>(TYPES.Warrior);

expect(ninja.fight()).eql("cut!"); // true
expect(ninja.sneak()).eql("hit!"); // true
```

我们可以看到 `Katana` 财务报告和审定财务报表 `Shuriken` 成功解决并注入 `Ninja`。 。 。 .

VersifyJS支持ES5和ES6,可以不用TypeScript工作. 头去 [**JavaScript 示例**](https://github.com/inversify/InversifyJS/blob/master/wiki/basic_js_example.md) 学习更多!

## \* 逆JS特征和API

让我们来看看"VersifyJS"的特征!

-   [课程支持](https://github.com/inversify/InversifyJS/blob/master/wiki/classes_as_id.md)
-   [支持符号](https://github.com/inversify/InversifyJS/blob/master/wiki/symbols_as_id.md)
-   [集装箱 API](https://github.com/inversify/InversifyJS/blob/master/wiki/container_api.md)
-   [宣布容器模块](https://github.com/inversify/InversifyJS/blob/master/wiki/container_modules.md)
-   [集装箱快照](https://github.com/inversify/InversifyJS/blob/master/wiki/container_snapshots.md)
-   [控制依赖范围](https://github.com/inversify/InversifyJS/blob/master/wiki/scope.md)
-   [声明可选依赖性](https://github.com/inversify/InversifyJS/blob/master/wiki/optional_dependencies.md)
-   [注入常数或动态值](https://github.com/inversify/InversifyJS/blob/master/wiki/value_injection.md)
-   [注入类构造器](https://github.com/inversify/InversifyJS/blob/master/wiki/constructor_injection.md)
-   [注入工厂](https://github.com/inversify/InversifyJS/blob/master/wiki/factory_injection.md)
-   [汽车厂](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_factory.md)
-   [自动命名工厂](https://github.com/inversify/InversifyJS/blob/master/wiki/auto_named_factory.md)
-   [注入提供者(同步工厂)](https://github.com/inversify/InversifyJS/blob/master/wiki/provider_injection.md)
-   [激活处理器](https://github.com/inversify/InversifyJS/blob/master/wiki/activation_handler.md)
-   [解除处理器](https://github.com/inversify/InversifyJS/blob/master/wiki/deactivation_handler.md)
-   [后构造装饰器](https://github.com/inversify/InversifyJS/blob/master/wiki/post_construct.md)
-   [中间软件](https://github.com/inversify/InversifyJS/blob/master/wiki/middleware.md)
-   [多注入](https://github.com/inversify/InversifyJS/blob/master/wiki/multi_injection.md)
-   [标记绑定](https://github.com/inversify/InversifyJS/blob/master/wiki/tagged_bindings.md)
-   [创建您的标签装饰器](https://github.com/inversify/InversifyJS/blob/master/wiki/custom_tag_decorators.md)
-   [命名装订](https://github.com/inversify/InversifyJS/blob/master/wiki/named_bindings.md)
-   [默认目标](https://github.com/inversify/InversifyJS/blob/master/wiki/default_targets.md)
-   [支持分级的DI系统](https://github.com/inversify/InversifyJS/blob/master/wiki/hierarchical_di.md)
-   [背景绑定和 @ targetName](https://github.com/inversify/InversifyJS/blob/master/wiki/contextual_bindings.md)
-   [财产注入](https://github.com/inversify/InversifyJS/blob/master/wiki/property_injection.md)
-   [循环依赖关系](https://github.com/inversify/InversifyJS/blob/master/wiki/circular_dependencies.md)
-   [继承](https://github.com/inversify/InversifyJS/blob/master/wiki/inheritance.md)

请参看 [维基百科](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) 其他细节.

## 生态系统

为了提供最新发展经验,我们还致力于:

-   [中间软件扩展](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#extensions)。 。 。 .
-   [开发工具](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#development-tools)。 。 。 .
-   [实例](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md#examples)。 。 。 .

请参看 [生态系统维基页面](https://github.com/inversify/InversifyJS/blob/master/wiki/ecosystem.md) 学习更多.

## 支助

如果你有经验 我们很乐意帮忙 您可以使用 [问题页面](https://github.com/inversify/InversifyJS/issues) 或 [聊天](https://gitter.im/inversify/InversifyJS)。也可以在 [堆叠溢出](http://stackoverflow.com/tags/inversifyjs) 使用 `inversifyjs` 标签.

如果你想与开发团队分享你的想法或加入我们,就能够使用 [正式邮件列表](https://groups.google.com/forum/#!forum/inversifyjs)您可以检查 [维基百科](https://github.com/inversify/InversifyJS/blob/master/wiki/readme.md) 以学习更多关于逆JS内部.

## 鸣谢

谢谢大家 [捐助者](https://github.com/inversify/InversifyJS/graphs/contributors),所有使用 InversifyJS 的开发者,以及所有通过在线分享 InversifyJS 内容来帮助我们传播这个词的人. 没有你们的反馈和支持,这个项目是不可能实现的.

## 许可证

麻省理工学院许可证

版权: 2015-2017 [雷莫·扬森](http://www.remojansen.com/)

特此准许任何人免费获得本软件和相关文件文件("软件")的副本,不受限制地在软件中进行交易,包括不受限制地享有软件的使用、复制、修改、合并、出版、分发、分版和(或)销售的权利,并允许软件获得者这样做,但须符合下列条件: 1

上述版权通知和许可通知应载入软件的所有副本或大部分.

软件是提供的"AS IS", 没有任何种类的恐惧, 释放或被卷入, 包括但不限制在 危机的保障, 证明一个特定的目的和无关.

任何索赔、索赔或其他负债,无论是合同、交易或其他行为,产生于、产生于或涉及软件或软件的使用或其他交易的行为,都不得作为担保.

## 常见问题

### @gritcode/inversify 是什么？

JavaScript和Node\.js应用程序由TypeScript提供动力的强大的轻量级反转控制容器\.

### 如何安装 @gritcode/inversify？

在项目目录运行 npm install @gritcode/inversify，或使用 pnpm add / yarn add / bun add。

### @gritcode/inversify 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gritcode/inversify 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @gritcode/inversify 可以商用吗？

@gritcode/inversify 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @gritcode/inversify 的下载量有多少？

根据 npm 官方下载统计，@gritcode/inversify 在 2026/10/17 – 2026/11/15 这 30 天内被下载 6,329 次，日均约 211 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gritcode/inversify 还在维护吗？

最新版本 6\.0\.2 发布于 2024/05/30（2 年前）；至今共发布 1 个版本，其中过去 12 个月发布了 0 个；首次发布于 2024/05/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

