【问题标题】:Dependency Injected APIs in custom Actions自定义操作中的依赖注入 API
【发布时间】:2015-08-10 00:52:52
【问题描述】:

我目前正在将 Play 2.3 项目迁移到 Play 2.4 中,并且在这样做时遇到了一些问题。 从 Play 2.4 开始,Guice 将一些 API 作为 WSClient 和 DBApi 注入到控制器中。

class MyController @Inject() (ws: WSClient, db: DBApi) extends Controller {}

现在我面临的问题是我需要在一些自定义操作中使用这些 API,我想知道我应该如何为这些 API 提供操作。

一种明显的方法是将这些参数显式传递给操作,如下所示:

object MyAction(p: Privilege.Value, db: DBApi, ws: WSClient) extends ActionBuilder[Request]{}

然后像这样调用动作:

class MyController @Inject (db: DBApi, ws: WSClient) extends Controller {
  def blubb = MyAction(Privilege.admin, db, ws).async(parse.json) { implicit request =>
    Future.successful(Ok("just a demo"))
  }
}

但我宁愿以某种方式隐式提交那些注入的 API:

object MyAction(p: Privilege.Value)(implicit db: DBApi, ws: WSClient) extends ActionBuilder[RequestContext] {}

然后这样称呼它,就像我从那以后一样;-)

class MyController @Inject (implicit db: DBApi, ws: WSClient) extends Controller {
  def doSomething = MyAction(Privilege.admin).async(parse.json) { implicit request =>
    Future.successful(Ok("just a demo"))
  }
}

但这不起作用...

有谁知道如何处理这个问题?

最好的问候 塞缪尔

【问题讨论】:

  • 您是否尝试将其注入到动作中?^^
  • 能否提供代码示例? case class MyAction @Inject (ws: WSClient) extends ActionBuilder[Request]{} 不起作用,如果它是你的意思;-)
  • 您找到解决方案了吗,我正在努力解决同样的问题,似乎找不到好的解决方案。
  • @henrik 是的,我将其发布为答案 :-)

标签: scala dependency-injection playframework-2.0 guice


【解决方案1】:

感谢 Johan Andrén,我终于找到了解决方案:https://groups.google.com/forum/#!topic/play-framework/aUIjB2R6BE4

他基本上建议创建这样的特征:

trait Authentication {
  def db: DBApi
  def ws: WSClient

  case class DataAction(privilege: Privilege.Value) extends ActionBuilder[RequestContext] with I18nSupport {
    // use db and ws to do your thing
  }
}

然后将其混合到所需的控制器中。

class MyController @Inject (val db: DBApi, val ws: WSClient) extends Controller with Authentication {
  def doSomething = Authenticated(Privilege.admin).async(parse.json) { implicit request =>
    Future.successful(Ok("just a demo"))
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-26
    • 2017-05-04
    • 1970-01-01
    • 2012-11-12
    相关资源
    最近更新 更多