将Play依赖注入模块配置为特征

时间:2018-06-15 14:13:58

标签: dependency-injection playframework

Play module scaladocs

  

强烈建议除了为JSR-330 DI提供模块外,该插件还提供了手动构建模块的Scala特性。这允许使用模块而无需运行时依赖注入提供程序。

如果我的模块的构造取决于play.api.Configuration,我可以使用ConfigFactory.load("application")创建该依赖关系,然后像我这样为我的模块创建一个工厂:

object MyModule {
  def apply(config: Config) = {
    val credentials = /* construct from config */
    new MyModule(credentials)
  }
}

我想我想知道,如果模块需要自己的依赖注入资源,我应该如何在特征中构建模块?如果我的特质需要其他内容,例如environment

,该怎么办?

1 个答案:

答案 0 :(得分:0)

您可以在特征中定义抽象成员。这意味着需要您的模块的代码必须提供这些代码。比如你的例子

// your definition
trait MyModuleComponents {
  def configuration: Configuration

  lazy val module = new MyModule(configuration)
}

// usage
class MyApp extends MyModuleComponents {
  // provide configuration here
  val configuration = ConfigFactory.load("application")

  // use module
  module.doSomething()
}

有关更好的示例,您可以查看how play does it for WsClient例如

相关问题