{"id":14969180,"url":"https://github.com/fastify/fastify-awilix","last_synced_at":"2025-05-16T05:06:28.332Z","repository":{"id":37968842,"uuid":"322341505","full_name":"fastify/fastify-awilix","owner":"fastify","description":"Dependency injection support for fastify","archived":false,"fork":false,"pushed_at":"2025-05-13T13:31:23.000Z","size":157,"stargazers_count":112,"open_issues_count":0,"forks_count":12,"subscribers_count":18,"default_branch":"main","last_synced_at":"2025-05-13T14:30:44.328Z","etag":null,"topics":["fastify","fastify-plugin"],"latest_commit_sha":null,"homepage":"https://npmjs.com/package/@fastify/awilix","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/fastify.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"fastify","open_collective":"fastify"}},"created_at":"2020-12-17T15:50:11.000Z","updated_at":"2025-05-13T13:10:59.000Z","dependencies_parsed_at":"2023-02-06T17:00:34.259Z","dependency_job_id":"d798f3d9-bd29-4768-a140-77f736a4e084","html_url":"https://github.com/fastify/fastify-awilix","commit_stats":{"total_commits":147,"total_committers":14,"mean_commits":10.5,"dds":0.45578231292517,"last_synced_commit":"80fbf5adcdaf488d1ec646914f9a92e9c0a020a4"},"previous_names":[],"tags_count":15,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-awilix","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-awilix/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-awilix/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/fastify%2Ffastify-awilix/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/fastify","download_url":"https://codeload.github.com/fastify/fastify-awilix/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254471061,"owners_count":22076585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["fastify","fastify-plugin"],"created_at":"2024-09-24T13:41:18.104Z","updated_at":"2025-05-16T05:06:23.320Z","avatar_url":"https://github.com/fastify.png","language":"JavaScript","readme":"# @fastify/awilix\n\n[![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)\n[![NPM version](https://img.shields.io/npm/v/@fastify/awilix)](https://www.npmjs.com/package/@fastify/awilix)\n[![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)\n\nDependency injection support for fastify framework, using [awilix](https://github.com/jeffijoe/awilix).\n\n## Getting started\n\nFirst, install the package and awilix:\n\n```bash\nnpm i @fastify/awilix awilix\n```\n\nNext, set up the plugin:\n\n```js\nconst { fastifyAwilixPlugin } = require('@fastify/awilix')\nconst fastify = require('fastify')\n\napp = fastify({ logger: true })\napp.register(fastifyAwilixPlugin, {\n  disposeOnClose: true,\n  disposeOnResponse: true,\n  strictBooleanEnforced: true\n})\n```\n\nThen, register some modules for injection:\n\n```js\nconst {\n  diContainer, // this is an alias for diContainerProxy\n  diContainerClassic, // this instance will be used for `injectionMode = 'CLASSIC'`\n  diContainerProxy // this instance will be used by default\n} = require('@fastify/awilix')\nconst { asClass, asFunction, Lifetime } = require('awilix')\n\n// Code from the previous example goes here\n\ndiContainer.register({\n  userRepository: asClass(UserRepository, {\n    lifetime: Lifetime.SINGLETON,\n    dispose: (module) =\u003e module.dispose(),\n  }),\n})\n\napp.addHook('onRequest', (request, reply, done) =\u003e {\n  request.diScope.register({\n    userService: asFunction(\n      ({ userRepository }) =\u003e {\n        return new UserService(userRepository, request.params.countryId)\n      },\n      {\n        lifetime: Lifetime.SCOPED,\n        dispose: (module) =\u003e module.dispose(),\n      }\n    ),\n  })\n  done()\n})\n```\n\nNote 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](https://github.com/jeffijoe/awilix) for more details.\n\nAfter 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:\n\n```js\napp.post('/', async (req, res) =\u003e {\n  const userRepositoryForReq = req.diScope.resolve('userRepository')\n  const userRepositoryForApp = app.diContainer.resolve('userRepository') // This returns exact same result as the previous line\n  const userService = req.diScope.resolve('userService')\n\n  // Logic goes here\n\n  res.send({\n    status: 'OK',\n  })\n})\n```\n\n## Plugin options\n\n`injectionMode` - whether to use PROXY or CLASSIC injection mode. See [awilix documentation](https://www.npmjs.com/package/awilix#injection-modes) for details. Default is 'PROXY'.\n\n`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.\n\n`disposeOnClose` - automatically invoke configured `dispose` for app-level `diContainer` hooks when the fastify instance is closed.\nDisposal is triggered within an `onClose` fastify hook.\nDefault value is `true`\n\n`disposeOnResponse` - automatically invoke configured `dispose` for request-level `diScope` hooks after the reply is sent.\nDisposal is triggered within `onResponse` fastify hook.\nDefault value is `true`\n\n`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.\nDefault value is `false`\n\n`asyncDispose` - whether to process `asyncDispose` fields in DI resolver configuration when closing the fastify app. Disabling this will make app closing slightly faster.\nDefault value is `false`\n\n`eagerInject` - whether to process `eagerInject` fields in DI resolver configuration, which instantiates and caches module immediately. Disabling this will make app startup slightly faster.\nDefault value is `false`\n\n`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`). It is recommended to set this to `true`, which will be a default value in the next semver major release.\nDefault value is `false`\n\n## Defining classes\n\nAll 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\nof the dependencies object match keys used in registering modules:\n\n```js\nclass UserService {\n  constructor({ userRepository }) {\n    this.userRepository = userRepository\n  }\n\n  dispose() {\n    // Disposal logic goes here\n  }\n}\n\nclass UserRepository {\n  constructor() {\n    // Constructor logic goes here\n  }\n\n  dispose() {\n    // Disposal logic goes here\n  }\n}\n\ndiContainer.register({\n  userService: asClass(UserService, {\n    lifetime: Lifetime.SINGLETON,\n    dispose: (module) =\u003e module.dispose(),\n  }),\n  userRepository: asClass(UserRepository, {\n    lifetime: Lifetime.SINGLETON,\n    dispose: (module) =\u003e module.dispose(),\n  }),\n})\n```\n\n## Typescript usage\n\nBy default `@fastify/awilix` is using generic empty `Cradle` and `RequestCradle` interfaces, it is possible to extend them with your own types:\n\n`awilix` defines Cradle as a proxy, and calling getters on it will trigger a `container.resolve` for an according module. [Read more](https://github.com/jeffijoe/awilix#containercradle).\n\n```typescript\ndeclare module '@fastify/awilix' {\n  interface Cradle {\n    userService: UserService\n  }\n  interface RequestCradle {\n    user: User\n  }\n}\n//later, type is inferred correctly\nfastify.diContainer.cradle.userService\n// or\napp.diContainer.resolve('userService')\n// request scope\nrequest.diScope.resolve('userService')\nrequest.diScope.resolve('user')\n```\n\nFind more in [tests](lib/index.test-d.ts) or [examples in the awilix documentation](https://github.com/jeffijoe/awilix/blob/master/examples/typescript/src/index.ts).\n\n## Asynchronous init, dispose, and eager injection\n\n`fastify-awilix` supports extended awilix resolver options, provided by [awilix-manager](https://github.com/kibertoad/awilix-manager#getting-started):\n\n```js\nconst { diContainer, fastifyAwilixPlugin } = '@fastify/awilix'\nconst { asClass } = require('awilix')\n\ndiContainer.register(\n  'dependency1',\n  asClass(AsyncInitSetClass, {\n    lifetime: 'SINGLETON',\n    asyncInit: 'init',\n    asyncDispose: 'dispose',\n    eagerInject: true,\n  })\n)\n\napp = fastify()\nawait app.register(fastifyAwilixPlugin, { asyncInit: true, asyncDispose: true, eagerInject: true })\nawait app.ready()\n```\n\n## Advanced DI configuration\n\nFor more advanced use cases, check the official [awilix documentation](https://github.com/jeffijoe/awilix).\n\n## License\n\nLicensed under [MIT](./LICENSE).\n","funding_links":["https://github.com/sponsors/fastify","https://opencollective.com/fastify"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-awilix","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffastify%2Ffastify-awilix","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffastify%2Ffastify-awilix/lists"}