是否可以使用scala依赖注入注入scala对象?

时间:2014-10-13 21:25:32

标签: forms scala dependency-injection singleton scaldi

是否可以使用scaldi dependecy注射注入scala对象? 如果是这样,我怎样才能获得注射器?

我有一个SignUpForm对象,它必须是一个单独的...

object SignUpForm {

  val form = Form(
    mapping(
      "firstName" -> nonEmptyText,
      "lastName" -> nonEmptyText,
      "email" -> email.verifying(Constraints.userExists),
      "password" -> mapping (
        "main" -> nonEmptyText.verifying(Constraints.passwordLenth),
        "confirm" -> nonEmptyText
      )(Password.apply)(Password.unapply).verifying(Constraints.passwordConfirmation)
    )(Data.apply)(Data.unapply)

  )

  case class Password(
    main: String,
    confirm: String
  )

  case class Data(
    firstName: String,
    lastName: String,
    email: String,
    password: Password
  )
}

...和对象约束

object Constraints {

  val userService = inject[UserService]

  def passwordConfirmation: Constraint[Password] = Constraint("password.confirm"){ password =>
    if (password.main.equals(password.confirm)) Valid else Invalid(Seq(ValidationError("password doesnt equal the confirmation password", "password.main", "confirm")))
  }

  def passwordLenth: Constraint[String] = Constraint("password.length"){ password =>
    if (password.length >= 8) Valid else Invalid(Seq(ValidationError("The minimum password length is " + 8 + " characters", "password.main", "length")))
  }

  def userExists: Constraint[String] = Constraint("user.exists"){ email =>
    if (userExistsWithEmail(email.toLowerCase)) Valid else Invalid(Seq(ValidationError("The user with email " + email + " already exists", "user", "email")))
  } ...

这是问题 - > userservice需要注入,但只要没有作为构造函数参数传递的隐式Injector就不能注入(由于我们在这里有一个对象,这是不可能的)

...
private def userExistsWithEmail(email: String):Boolean = {
    val result = Await.result(userService.retrieve(LoginInfo(CredentialsProvider.Credentials, email)),1 seconds)

     result match {
      case Some(u) => true
      case None => false
    }
  }
}

......我该如何解决这个问题?

提前致谢

1 个答案:

答案 0 :(得分:2)

看起来你已经回答了自己的问题。对象是您无法初始化的单例,因此不能有构造函数参数。

将您的Constraints对象转换为一个类,然后当您(或您的DI框架)创建它时,您将能够注入依赖项。