繁体   English   中英

玩2.5剪影4 - DI与guice

[英]Play 2.5 Silhouette 4 - DI with guice

语言:Scala; 框架:播放2.5; 图书馆:剪影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
    )
  }

提前致谢。

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

使用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]]{})

关于介绍这些功能的特性有一个描述权,请看这里: 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)
    ...
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM