加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 播放框架:Dependecy Inject Action Builder

发布时间:2020-12-16 09:24:04 所属栏目:安全 来源:网络整理
导读:由于Play Framework 2.4有可能使用依赖注入(使用Guice). 在我使用ActionBuilders中的对象(例如AuthenticationService)之前: object AuthenticatedAction extends ActionBuilder[AuthenticatedRequest] { override def invokeBlock[A](request: Request[A],b
由于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不再是一个对象,而是一个类.我如何仍然在我的ActionBuilder中使用AuthenticationService?

解决方法

将身份验证服务中的动作构建器定义为抽象字段.然后将它们混合到您的控制器中,您可以向其注入服务.例如:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读