Last active
August 11, 2017 18:24
-
-
Save crizstian/5c4c2f15872902949bf58712a5a0b0a5 to your computer and use it in GitHub Desktop.
Example of dependency injection registration
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!