(播放2.4)特征中的依赖注入?

Max*_*Max 7 dependency-injection scala guice playframework

在游戏2.4中,是否可以在特征中使用依赖注入?

有什么例子吗?

谢谢.

akk*_*kie 6

我在这里谈论与Guice的运行时DI,因为它是Play使用的默认方法.其他DI方法或框架可能会有所不同.

由于特征不可实例化,因此无法将依赖关系注入特征.特征没有用于定义依赖关系的构造函数.

在Play中,只要Application trait在范围内,您就可以直接使用注入器.但这不是生产代码中的好习惯.在测试代​​码中,这将是一个选项.

class MySpec extends PlaySpecification {
  "My test" should {
    "Use the injector" in new WithApplication extends Context {
      val messages = Messages(Lang("en-US"), messagesApi)
    } 
  }

  trait Context extends Scope {
    self: WithApplication =>

    val messagesApi = app.injector.instanceOf[MessagesApi]
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 因此,在生产代码中,*是*推荐的好方法,例如当您需要在"安全"特征中使用"AuthService"时:http://stackoverflow.com/q/34223440/56285 (7认同)