Skip to content

Instantly share code, notes, and snippets.

@crizstian
Last active August 11, 2017 18:24
Show Gist options
  • Save crizstian/5c4c2f15872902949bf58712a5a0b0a5 to your computer and use it in GitHub Desktop.
Save crizstian/5c4c2f15872902949bf58712a5a0b0a5 to your computer and use it in GitHub Desktop.
Example of dependency injection registration
const { createContainer, asValue, asFunction, asClass } = require('awilix')
function initDI ({serverSettings, dbSettings, database, models, services}, mediator) {
mediator.once('init', () => {
mediator.on('db.ready', (db) => {
const container = createContainer()
// loading dependecies in a single source of truth
container.register({
database: asValue(db).singleton(),
validate: asValue(models.validate),
booking: asValue(models.booking),
user: asValue(models.booking),
ticket: asValue(models.booking),
ObjectID: asClass(database.ObjectID),
serverSettings: asValue(serverSettings),
paymentService: asValue(services.paymentService),
notificationService: asValue(services.notificationService)
})
// we emit the container to be able to use it in the API
mediator.emit('di.ready', container)
})
mediator.on('db.error', (err) => {
mediator.emit('di.error', err)
})
database.connect(dbSettings, mediator)
mediator.emit('boot.ready')
})
}
module.exports.initDI = initDI
@caesaneer
Copy link

Hello,

I have implemented this example and everything works great except for the fact that I cannot set my DB to a singleton. I get:

(node:94072) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: (0 , _awilix.asValue)(...).singleton is not a function(node:94072) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Any ideas what's going on here?

Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment