玩 scala - 通过 Guice Injector 实例注入依赖项

Play with scala - Injecting dependencies through an instance of Guice Injector

我的应用程序使用 Play-2.4.2/Scala-2.11.6,内置 Guice 支持 DI

我所有的 DAO 都将一个实现绑定到一个接口,如下所示,这应该是 Guice 中最简单的方法

@ImplementedBy(classOf[PersonDAOImpl])
trait PersonDAO {
}

class PersonDAOImpl @Inject()
(
(@NamedDatabase("mysql")protected val dbConfigProvider: DatabaseConfigProvider,
 protected val cache : CacheApi) extends PersonDAO with SQLWrapper {
..
...

}

以上实现不需要添加任何模块来提供绑定。

现在出于某种原因,我不想将依赖项注入 Books class 的构造函数 使用@Inject 注释。所以,我尝试如下注入它

class Books {

  val injector = Guice.createInjector()

  val personDAO : PersonDAO = injector.getInstance(classOf[PersonDAOImpl])

..
...

}

但这会抛出一个 guice 配置异常:

Caused by: com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for play.api.cache.CacheApi was bound.
  while locating play.api.cache.CacheApi
    for parameter 1 at schema.PersonDAOImpl.<init>
  while locating PersonDAO

2)  No implementation for play.api.db.slick.DatabaseConfigProvider annotated with @play.db.NamedDatabase(value=mysql) was bound.
  while locating play.api.cache.CacheApi
    for parameter 2 at schema.PersonDAOImpl.<init>  while locating PersonDAO

现在需要做什么?在这种情况下,我的方法是对还是错?有人可以帮我解决这个问题吗?提前致谢。

您可以使用 Injector from the current Play Application.

import play.api.{ Application, Play }
import play.api.inject.Injector

val currentApp: Application = Play.current
val injector: Injector = currentApp.injector
// in short play.api.Play.current.injector

// Then use the injector
import play.api.inject.ApplicationLifecycle
current.injector.instanceOf[ApplicationLifecycle].
  addStopHook { () => ??? }

(参见使用 injectorPlay plugin for ReactiveMongo 的示例)