0

I'm using Awilix in my code for Dependecy Injection and I have this User class.

    class User {
    constructor(opts){
        this.validator = opts.validator
    }

    async validateUsername(username) {
        this.validator.username(username)
    }
    async validatePassword(password) {
            this.validator.password(password)
        }


}


    module.exports = User

Container:

const User = require('../../user/User')
const Validator = require('../../user/Validator')
const awilix = require('awilix')

const container = awilix.createContainer({
  injectionMode: awilix.InjectionMode.PROXY
})

container.register({
  user: awilix.asClass(User),
  validator: awilix.asClass(Validator),

})


module.exports = container

What I want do is to add "username" and "password" in the constructor, because those are properties of the class "User". So, it will look like this:

class User {
  constructor(opts, username, password){
      this.validator = opts.validator
      this.username = username 
      this.password = password 
  }

  async validateUsername() {
      this.validator.username(this.username)
  }
  async validatePassword() {
      this.validator.password(this.password)
      }
}


  module.exports = User

I can't figure out how to pass arguments through the constructor with Awilix.

1 Answers1

0

I am not sure if you still need an answer for your question but maybe someone in the near future will going to stuck like me.

container.register({ 
   user: awilix.addClass(User).inject(() => { username: 'random', ... }),
   ....
})

Link to the documentation

entymon
  • 62
  • 5