0

在 scaldi 中,可以有implicit inj: Injectorfor 类,并且Injector在 scaldi 中定义时无需任何附加代码即可传递Module

class MessageService(implicit inj: Injector)
          extends Injectable {

  val officialGreeting =
    inject [String] (identified by "greeting.official")

  def getGreetMessage(name: String) =
    s"$officialGreeting, $name!"
}

//Module
class UserModule extends Module {
  bind [MessageService] to new MessageService

  binding identifiedBy "greeting.official" to "Welcome"
}

如何在一个特质中做同样的事情?

class MessageService() {

  val officialGreeting =
    inject [String] (identified by "greeting.official")

  def getGreetMessage(name: String) =
    s"$officialGreeting, $name!"
}

trait MessageServiceReportingMixin extends MessageService with Injectable {

  implicit val inj: Injector 

  val reporter = inject[Reporter]

  override def getGreetMessage(name: String) = reporter.report(super.getGreetMessage(name))
}

//Module
class UserModule extends Module {

  //I WANT TO AVOID THIS
  bind [MessageService] to new MessageService() with MessageServiceReportingMixin {
    val inj = injector
  }

  //I WANT TO DO THIS INSTEAD
  bind [MessageService] to new MessageService() with MessageServiceReportingMixin

  binding identifiedBy "greeting.official" to "Welcome"
}

implicit val inj: Injector = implicitly进行这项工作会有任何问题吗?还请评论将报告作为混合从主要类中分离出来的整体风格

4

0 回答 0