【问题标题】:(Play 2.4) Dependency injection in a trait?(播放 2.4)特征中的依赖注入?
【发布时间】:2015-11-02 14:12:49
【问题描述】:

在 play 2.4 中,是否可以在 trait 中使用依赖注入?

有例子吗?

谢谢。

【问题讨论】:

    标签: scala playframework dependency-injection guice


    【解决方案1】:

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

    不可能将依赖项注入到 trait 中,因为 trait 不可实例化。 trait 没有构造函数来定义依赖关系。

    在 Play 中,只要 Application 特征在范围内,您就可以直接使用注入器。但这在生产代码中不被认为是好的做法。在测试代​​码中,这是一个选项。

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多