播放框架:依赖项注入操作生成器 [英] Play Framework: Dependency Inject Action Builder

查看:69
本文介绍了播放框架:依赖项注入操作生成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自Play Framework 2.4起,就有可能使用依赖注入(与Guice配合使用).

since Play Framework 2.4 there is the possibility to use dependency injection (with Guice).

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

Before I used objects (for example AuthenticationService) in my ActionBuilders:

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

现在,AuthenticationService不再是对象,而是一个类.我如何仍可以在ActionBuilder中使用AuthenticationService?

Now AuthenticationService is not an object anymore, but a class. How can I still use the AuthenticationService in my ActionBuilder?

推荐答案

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

Define your action builders inside a trait with the authentication service as an abstract field. Then mix them into your controllers, into which you inject the service. For example:

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!")
  }
}

这篇关于播放框架:依赖项注入操作生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆