簡體   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