# @fastify/awilix 中文文档

规范地址：https://npmcn.com/package/%40fastify/awilix/

版本：8\.3\.2
npm 元数据更新时间：2026-10-24T13:58:36.112Z
中文译文更新时间：2026-11-14T11:22:20.476Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：39.8 kB，16 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：awilix \>=9\.0\.0，fastify ^5\.0\.0
- 首次发布：2022-05-26T23:04:48.756Z
- 最新版本发布：2026-10-24T13:58:35.769Z
- 近 30 天下载量：268034（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：22（近 12 个月 5 个）

## 中文简介

对固化框架的依赖性注射支持

## 安装

```sh
npm install @fastify/awilix
```

也可以使用：`pnpm add @fastify/awilix`、`yarn add @fastify/awilix`、`bun add @fastify/awilix`

## README

# @ fastify/ awilix (中文(简体) )

[![CI](https://github.com/fastify/fastify-awilix/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-awilix/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/awilix)](https://www.npmjs.com/package/@fastify/awilix) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

对固化框架的依赖性注射支持,使用 [阿维利克斯](https://github.com/jeffijoe/awilix)。 。 。 .

## 开始

首先,安装软件包和awilix:

```bash
npm i @fastify/awilix awilix
```

接下来,设置插件 :

```js
const { fastifyAwilixPlugin } = require('@fastify/awilix')
const fastify = require('fastify')

app = fastify({ logger: true })
app.register(fastifyAwilixPlugin, {
  disposeOnClose: true,
  disposeOnResponse: true,
  strictBooleanEnforced: true
})
```

然后,注册一些模块进行注射:

```js
const {
  diContainer, // this is an alias for diContainerProxy
  diContainerClassic, // this instance will be used for `injectionMode = 'CLASSIC'`
  diContainerProxy // this instance will be used by default
} = require('@fastify/awilix')
const { asClass, asFunction, Lifetime } = require('awilix')

// Code from the previous example goes here

diContainer.register({
  userRepository: asClass(UserRepository, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
})

app.addHook('onRequest', (request, reply, done) => {
  request.diScope.register({
    userService: asFunction(
      ({ userRepository }) => {
        return new UserService(userRepository, request.params.countryId)
      },
      {
        lifetime: Lifetime.SCOPED,
        dispose: (module) => module.dispose(),
      }
    ),
  })
  done()
})
```

请注意,没有严格的使用类的要求,也可以登记原始值,使用其中之一 `asFunction()`,或 `asValue()`检查 [awilix 文档](https://github.com/jeffijoe/awilix) 更多细节.

在所有模块注册后,可以通过从应用范围注入的依赖性来解决 `diContainer` 和请求范围d `diScope`。注意: `diScope` 允许从父程序解析所有模块 `diContainer` 范围 :

```js
app.post('/', async (req, res) => {
  const userRepositoryForReq = req.diScope.resolve('userRepository')
  const userRepositoryForApp = app.diContainer.resolve('userRepository') // This returns exact same result as the previous line
  const userService = req.diScope.resolve('userService')

  // Logic goes here

  res.send({
    status: 'OK',
  })
})
```

## 插件选项

`injectionMode` - 使用PROXY或CLASIC注射方式。 见 [awilix 文档](https://www.npmjs.com/package/awilix#injection-modes) 详细情况。 默认为“ PROXY ” .

`container` - 预设的 AwilixContainer 实例,该插件应当使用。 默认情况下,插件会使用自己的实例. 注意你无法同时说明 `injectionMode` 财务报告和审定财务报表 `container` 参数在同一时间.

`disposeOnClose` - 自动引用已配置 `dispose` 应用级 `diContainer` 结接实例关闭时用钩子. 处置在 `onClose` 接钩. 默认值是 `true`

`disposeOnResponse` - 自动引用已配置 `dispose` 请求一级 `diScope` 答发后取钩. 处置在 `onResponse` 接钩. 默认值是 `true`

`asyncInit` - 是否处理 `asyncInit` 字段。 请注意,所有具有激活功能的依赖性都会被急切地瞬间切入. 失效将使应用程序启动速度略快一些. 默认值是 `true`

`asyncDispose` - 是否处理 `asyncDispose` 字段。 关闭会让应用程序收尾稍快一点. 默认值是 `true`

`eagerInject` - 是否处理 `eagerInject` 字段在 DI 解析器配置中,该解析器立即对模块进行即时和缓存。 失效将使应用程序启动速度略快一些. 默认值是 `true`

`strictBooleanEnforced` - 如果 `enabled` 字段在解析器配置中设置一个不支持的值(任何与 `true` 财务报告和审定财务报表 `false`) (中文(简体) ). 默认值是 `true`

`enableDebugLogging` 是否在每次依赖开始和完成初始化时日志 `asyncInit` 阶段。 这对于初始化期间调试超时问题很有用,因为它有助于识别哪些依赖性被挂起或者设置花费了过多的时间. 默认值是 `false`

`loggerFn` - 处理日志消息的回调功能,当 `enableDebugLogging` 已启用。 该函数收到包含日志消息的单一字符串参数. 默认值是 `console.log`

`onNonBlockingInitError` - 对登记在册的依赖关系所抛出的错误召回 `asyncInit: { nonBlocking: true }`,则在 `asyncInit` 阶段。 该函数收到依赖名称和错误. 默认值以 `console.error`

## 定义类

所有依赖性模块均使用构造器注入(用于 `asClass`)或函数参数(用于 `asFunction`),通过传递集合依赖对象,其中键 对象匹配用于注册模块的密钥 :

```js
class UserService {
  constructor({ userRepository }) {
    this.userRepository = userRepository
  }

  dispose() {
    // Disposal logic goes here
  }
}

class UserRepository {
  constructor() {
    // Constructor logic goes here
  }

  dispose() {
    // Disposal logic goes here
  }
}

diContainer.register({
  userService: asClass(UserService, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
  userRepository: asClass(UserRepository, {
    lifetime: Lifetime.SINGLETON,
    dispose: (module) => module.dispose(),
  }),
})
```

## 字迹使用

默认 `@fastify/awilix` 正在使用通用空 `Cradle` 财务报告和审定财务报表 `RequestCradle` 界面,可以用您自己的类型扩展它们:

`awilix` 将 Cradle 定义为代理, 并调用它的获取器将触发一个 `container.resolve` 用于给定模块. [更多信息](https://github.com/jeffijoe/awilix#containercradle)。 。 。 .

```typescript
declare module '@fastify/awilix' {
  interface Cradle {
    userService: UserService
  }
  interface RequestCradle {
    user: User
  }
}
//later, type is inferred correctly
fastify.diContainer.cradle.userService
// or
app.diContainer.resolve('userService')
// request scope
request.diScope.resolve('userService')
request.diScope.resolve('user')
```

查找更多内容 [测试](https://npmcn.com/package/%40fastify/awilix/lib/index.test-d.ts) 或者说 [awilix 文档中的例子](https://github.com/jeffijoe/awilix/blob/master/examples/typescript/src/index.ts)。 。 。 .

## 同步注射、处置和急切注射

`fastify-awilix` 支持扩展的 awilix 解析器选项,由 [awilix 管理器](https://github.com/kibertoad/awilix-manager#getting-started)数字 :

```js
const { diContainer, fastifyAwilixPlugin } = '@fastify/awilix'
const { asClass } = require('awilix')

diContainer.register(
  'dependency1',
  asClass(AsyncInitSetClass, {
    lifetime: 'SINGLETON',
    asyncInit: 'init',
    asyncDispose: 'dispose',
    eagerInject: true,
  })
)

app = fastify()
await app.register(fastifyAwilixPlugin, { asyncInit: true, asyncDispose: true, eagerInject: true })
await app.ready()
```

## 高级 DI 配置

对于更先进的使用案例,请检查官方 [awilix 文档](https://github.com/jeffijoe/awilix)。 。 。 .

## 许可证

许可证根据 [麻省理工学院](https://npmcn.com/package/%40fastify/awilix/LICENSE)。 。 。 .

## 常见问题

### @fastify/awilix 是什么？

对固化框架的依赖性注射支持

### 如何安装 @fastify/awilix？

在项目目录运行 npm install @fastify/awilix，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：awilix（\>=9\.0\.0）、fastify（^5\.0\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @fastify/awilix 支持 TypeScript 吗？

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

### @fastify/awilix 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/awilix 可以商用吗？

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

### @fastify/awilix 的下载量有多少？

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

### @fastify/awilix 还在维护吗？

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

