@fastify/awilix

中文文档
8.3.2发布于 2026/10/24MITTypeScriptCommonJS构建来源已验证近 30 天下载 26.8万

Dependency injection support for fastify framework

原始使用文档
文档目录7 节
  1. Getting started
  2. Plugin options
  3. Defining classes
  4. Typescript usage
  5. Asynchronous init, dispose, and eager injection
  6. Advanced DI configuration
  7. License

@fastify/awilix

CI NPM version neostandard javascript style

Dependency injection support for fastify framework, using awilix.

Getting started

First, install the package and awilix:

npm i @fastify/awilix awilix

Next, set up the plugin:

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

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

Then, register some modules for injection:

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()
})

Note that there is no strict requirement to use classes, it is also possible to register primitive values, using either asFunction(), or asValue(). Check awilix documentation for more details.

After all the modules are registered, they can be resolved with their dependencies injected from app-scoped diContainer and request-scoped diScope. Note that diScope allows resolving all modules from the parent diContainer scope:

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',
  })
})

Plugin options

injectionMode - whether to use PROXY or CLASSIC injection mode. See awilix documentation for details. Default is 'PROXY'.

container - pre-created AwilixContainer instance that should be used by the plugin. By default, the plugin uses its own instance. Note that you can't specify both injectionMode and container parameters at the same time.

disposeOnClose - automatically invoke configured dispose for app-level diContainer hooks when the fastify instance is closed. Disposal is triggered within an onClose fastify hook. Default value is true

disposeOnResponse - automatically invoke configured dispose for request-level diScope hooks after the reply is sent. Disposal is triggered within onResponse fastify hook. Default value is true

asyncInit - whether to process asyncInit fields in DI resolver configuration. Note that all dependencies with asyncInit enabled are instantiated eagerly. Disabling this will make app startup slightly faster. Default value is true

asyncDispose - whether to process asyncDispose fields in DI resolver configuration when closing the fastify app. Disabling this will make app closing slightly faster. Default value is true

eagerInject - whether to process eagerInject fields in DI resolver configuration, which instantiates and caches module immediately. Disabling this will make app startup slightly faster. Default value is true

strictBooleanEnforced - whether to throw an error if enabled field in a resolver configuration is set with an unsupported value (anything different from true and false). Default value is true

enableDebugLogging - whether to log when each dependency starts and finishes initializing during the asyncInit phase. This is useful for debugging timeout issues during initialization, as it helps identify which dependencies are hanging or taking excessive time to set up. Default value is false

loggerFn - callback function for handling log messages when enableDebugLogging is enabled. The function receives a single string parameter containing the log message. Default value is console.log

onNonBlockingInitError - callback for errors thrown by dependencies registered with asyncInit: { nonBlocking: true }, which are not awaited during the asyncInit phase. The function receives the dependency name and the error. Default value logs them with console.error

Defining classes

All dependency modules are resolved using either the constructor injection (for asClass) or the function argument (for asFunction), by passing the aggregated dependencies object, where keys of the dependencies object match keys used in registering modules:

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(),
  }),
})

Typescript usage

By default @fastify/awilix is using generic empty Cradle and RequestCradle interfaces, it is possible to extend them with your own types:

awilix defines Cradle as a proxy, and calling getters on it will trigger a container.resolve for an according module. Read more.

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')

Find more in tests or examples in the awilix documentation.

Asynchronous init, dispose, and eager injection

fastify-awilix supports extended awilix resolver options, provided by awilix-manager:

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()

Advanced DI configuration

For more advanced use cases, check the official awilix documentation.

License

Licensed under MIT.

版本与发布记录

@fastify/awilix 共发布 22 个版本,首次发布于 2022/05/27;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.3.2latest2026/10/2420 天前
8.3.12026/10/081 个月前
8.3.02026/09/241 个月前
8.2.12026/08/093 个月前
8.2.02025/12/0511 个月前
8.1.02025/11/131 年前

其他发布通道:next → 6.0.0。

关于 @fastify/awilix 的常见问题

@fastify/awilix 是什么?

Dependency injection support for fastify framework

如何安装 @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 和提交记录判断。