如何在Play Guice模块中访问请求?

Pri*_*a R 3 request guice playframework

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

现在我有Service类,比如说CustomerService.

class CustomerService(val systemID: String) {
    // Implementation
}
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:

已经简化了上面的代码.我的实际代码使用接口.我怎样才能使用辅助注射?

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)
{
}
Run Code Online (Sandbox Code Playgroud)

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

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

ret*_*hab 6

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

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

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

object CustomerService {
  trait Factory {
    def apply(val systemID: String): CustomerService
  }
}
Run Code Online (Sandbox Code Playgroud)

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

class CustomerService @Inject() (@Assisted systemId: String) { .. }
Run Code Online (Sandbox Code Playgroud)

3.将工厂绑定在guice模块中:

install(new FactoryModuleBuilder()
  .implement(classOf[CustomerService], classOf[CustomerServiceImpl])
  .build(classOf[CustomerService.Factory]))
Run Code Online (Sandbox Code Playgroud)

4.最后在需要客户服务的地方注入工厂:

class MyController @Inject() (csFactory: CustomerService.Factory) { .. }
Run Code Online (Sandbox Code Playgroud)

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