播放 2.5 Silhouette 4 - DI with guice

Play 2.5 Silhouette 4 - DI with guice

语言:Scala; 架构:玩2.5; 库:Silhouette 4.0、Guice、scala-guice。

Silhouette 官方种子项目之一使用 guice 和 scala-guice (net.codingwell.scalaguice.ScalaModule) 编写 DI 配置。代码如下所示:

import net.codingwell.scalaguice.ScalaModule

class Module extends AbstractModule with ScalaModule{

  /**
    * Configures the module.
    */
  def configure() {

    bind[Silhouette[MyEnv]].to[SilhouetteProvider[MyEnv]]
    bind[SecuredErrorHandler].to[ErrorHandler]
    bind[UnsecuredErrorHandler].to[ErrorHandler]
    bind[IdentityService[User]].to[UserService]

我想知道,如果没有来自 net.codingwell.scalaguice 库的魔法,这段代码会是什么样子。有人可以仅使用原始 guice 重写这些绑定吗?

另外我还有这个代码:

@Provides
  def provideEnvironment(
      userService: UserService,
      authenticatorService: AuthenticatorService[CookieAuthenticator],
      eventBus: EventBus
  ): Environment[MyEnv] = {
    Environment[MyEnv](
      userService,
      authenticatorService,
      Seq(),
      eventBus
    )
  }

提前致谢。

介绍功能的trait上有说明,看这里:https://github.com/codingwell/scala-guice/blob/develop/src/main/scala/net/codingwell/scalaguice/ScalaModule.scala#L32

因此,在这种情况下,它将转换为如下内容:

class SilhouetteModule extends AbstractModule {

  def configure {
    bind(classOf[Silhouette[DefaultEnv]]).to(classOf[SilhouetteProvider[DefaultEnv]])
    bind(classOf[CacheLayer]).to(classOf[PlayCacheLayer])

    bind(classOf[IDGenerator]).toInstance(new SecureRandomIDGenerator())
    bind(classOf[PasswordHasher]).toInstance(new BCryptPasswordHasher)
    ...
}

感谢 insan-e 指出了正确的方向。这是显示如何使用 guice 注入通用实现的答案:

Inject Generic Implementation using Guice

因此,如果从等式中删除 scala-guice 库,绑定可以这样写:

import com.google.inject.{AbstractModule, Provides, TypeLiteral}
class Module extends AbstractModule {

  /**
    * Configures the module.
    */
  def configure() {
    bind(new TypeLiteral[Silhouette[MyEnv]]{}).to(new TypeLiteral[SilhouetteProvider[MyEnv]]{})