(Play 2.4) Dependency injection in a trait?

为君一笑 提交于 2019-12-08 17:40:06

问题


In play 2.4, is it possible to use dependency injection in a trait ?

Is there any example ?

Thanks.


回答1:


I talk about runtime DI with Guice here because it's the default method used by Play. Other DI methods or frameworks may differ here.

It isn't possible to inject a dependency into a trait because a trait isn't instantiable. A trait doesn't have a constructor to define the dependencies.

In Play you could use the injector directly as long as the Application trait is in scope. But this isn't considered good practice in production code. In test code this would be an option.

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]
  }
}


来源:https://stackoverflow.com/questions/31923365/play-2-4-dependency-injection-in-a-trait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!