2

是否可以使用 scaldi 依赖注入注入 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
    }
  }
}

... 我怎么解决这个问题?

提前致谢

4

1 回答 1

2

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

将您的Constraints对象变成一个类,然后您就可以在您(或您的 DI 框架)创建它时注入依赖项。

于 2014-10-14T15:37:01.053 回答