Play Framework:Dependency Inject Action Builder

时间:2015-06-28 10:46:17

标签: scala playframework dependency-injection guice guice-3

因为Play Framework 2.4可以使用依赖注入(使用Guice)。

在我的ActionBuilders中使用对象(例如AuthenticationService)之前:

object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] {
  override def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
    ...
    AuthenticationService.authenticate (...)
    ...
  }
}

现在AuthenticationService不再是一个对象,而是一个类。如何在我的AuthenticationService中使用ActionBuilder

2 个答案:

答案 0 :(得分:27)

使用身份验证服务作为抽象字段在特征中定义操作构建器。然后将它们混合到您注入服务的控制器中。例如:

trait MyActionBuilders {
  // the abstract dependency
  def authService: AuthenticationService

  def AuthenticatedAction = new ActionBuilder[AuthenticatedRequest] {
    override def invokeBlock[A](request: Request[A], block(AuthenticatedRequest[A]) => Future[Result]): Future[Result] = {
      authService.authenticate(...)
      ...
    }
  }
}

和控制器:

@Singleton
class MyController @Inject()(authService: AuthenticationService) extends Controller with MyActionBuilders {    
  def myAction(...) = AuthenticatedAction { implicit request =>
    Ok("authenticated!")
  }
}

答案 1 :(得分:0)

我喜欢接受的答案,但由于某种原因,编译器无法识别authService引用。只需在方法签名中发送服务,我就可以很轻松地解决这个问题了......

class Authentication @Inject()(authenticationService: AuthenticationService) extends Controller with ActionBuilders {

  def testAuth = AuthenticatedAction(authenticationService).async { implicit request =>
    Future.successful(Ok("Authenticated!"))
  }

}