
Product
Introducing Socket Scanning for OpenVSX Extensions
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.
@fastify/awilix
Advanced tools
Dependency injection support for fastify framework, using awilix
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 })
Then, register some modules for injection:
const { diContainer } = 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',
})
})
disposeOnClose - automatically invoke configured dispose for app-level diContainer hooks when the fastify instance is closed.
Disposal is triggered within 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
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(UserRepository, {
lifetime: Lifetime.SINGLETON,
dispose: (module) => module.dispose(),
}),
userRepository: asClass(UserRepository, {
lifetime: Lifetime.SINGLETON,
dispose: (module) => module.dispose(),
}),
})
By default @fastify/awilix is using generic empty Cradle and RequestCradle interfaces, it is possible 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 in example from awilix documentation
If you prefer classic injection, you can use it like this:
const { fastifyAwilixPlugin } = require('@fastify/awilix/classic')
const fastify = require('fastify')
app = fastify({ logger: true })
app.register(fastifyAwilixPlugin, { disposeOnClose: true, disposeOnResponse: true })
For more advanced use-cases, check the official awilix documentation
FAQs
Dependency injection support for fastify framework
The npm package @fastify/awilix receives a total of 16,044 weekly downloads. As such, @fastify/awilix popularity was classified as popular.
We found that @fastify/awilix demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 17 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Product
Socket now scans OpenVSX extensions, giving teams early detection of risky behaviors, hidden capabilities, and supply chain threats in developer tools.

Product
Bringing supply chain security to the next generation of JavaScript package managers

Product
A safer, faster way to eliminate vulnerabilities without updating dependencies