【问题标题】:How can I access request in Play Guice Module?如何在 Play Guice 模块中访问请求?
【发布时间】:2016-03-12 16:25:48
【问题描述】:

我正在编写一个处理多个系统的应用程序。用户可以选择他想要使用的系统,我将该系统 ID 存储在会话(客户端会话)中

现在我有了服务类,比如说 CustomerService。

class CustomerService(val systemID: String) {
    // Implementation
}

我想使用 Guice 将 Customer 实例注入控制器。但我想用存储在会话中的 SystemID 实例化 CustomerService。

如何在 Guice 模块中访问request.session

编辑:

已经简化了我上面的代码。我的实际代码使用接口。我该如何使用辅助注射?

trait CustomerService(val systemID: String) {
    // Definition
}

object CustomerService{

  trait Factory {
    def apply(systemID: String) : CustomerService
  }

}

class DefaultCustomerService @Inject() (@Assisted systemID: String)
  extends CustomerService {
    // Definition
}

class CustomerController @Inject()(
                            val messagesApi: MessagesApi,
                            csFactory: CustomerService.Factory)
{
}

这给了我: CustomerService 是一个接口,而不是一个具体的类。无法创建 AssistedInject 工厂。

我不想将工厂放在DefaultCustomerService 下并在控制器中使用DefaultCustomerService.Factory。这是因为对于单元测试,我将使用 TestCustomerService 存根并希望依赖注入将 TestCustomerService 注入控制器而不是 DefaultCustomerService

【问题讨论】:

    标签: playframework request guice


    【解决方案1】:

    你不应该那样做。如果需要注入需要运行时值的实例,可以使用 guice 的 AssistedInject

    以下是如何在游戏中使用它:

    1。使用运行时值作为参数创建服务工厂:

    object CustomerService {
      trait Factory {
        def apply(val systemID: String): CustomerService
      }
    }
    

    2。使用辅助参数实现您的服务

    class CustomerService @Inject() (@Assisted systemId: String) { .. }
    

    3。在你的 guice 模块中绑定工厂:

    install(new FactoryModuleBuilder()
      .implement(classOf[CustomerService], classOf[CustomerServiceImpl])
      .build(classOf[CustomerService.Factory]))
    

    4。最后注入需要客服的工厂:

    class MyController @Inject() (csFactory: CustomerService.Factory) { .. }
    

    这是另一个辅助注入示例: https://www.playframework.com/documentation/2.5.x/ScalaTestingWebServiceClients

    【讨论】:

    • 感谢 rethab - 但请查看我在问题中的编辑。
    • FactoryModuleBuilder 有一个方法 'implement',您可以在其中将 trait 绑定到一个类。我想这就是你要找的。​​span>
    • 谢谢我找到了!如果您可以将其添加到您的答案中,我会接受。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2011-01-07
    相关资源
    最近更新 更多