在游戏中使用ActionBuilder创建自定义动作时使用guice [英] Using guice when creating a custom Action using ActionBuilder in play

查看:77
本文介绍了在游戏中使用ActionBuilder创建自定义动作时使用guice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ActionBuilder创建自定义动作时,如何使用guice?

How can I use guice when creating a custom Action using ActionBuilder?

如果将ActionBuilder从对象更改为类,似乎会抱怨找不到:值MyAction".

It seems to complain with "not found: value MyAction" if I change the ActionBuilder from a object to a class.

我有这个,但是不起作用:

I have this but it doesn't work:

case class MyModel(name: String, request: Request[A]) extends WrappedRequest[A](request)

class MyAction @Inject()(userService: UserService) extends ActionBuilder[MyModel] {
  def invokeBlock[A](request: Request[A], block: (MyModel[A]) => Future[SimpleResult]) = {
    val abc = loadAbc(request)
    block(new MyModel(abc, request))
  }

  def loadAbc(rh: RequestHeader): String {
    "abc" // just for testing
  }
}

因此将其从object更改为class会导致失败,我尝试将其保留为对象,但编译失败.

So changing it from an object to a class causes it to fail, and I tried keeping it as an object but then it doesn't compile correctly.

我该如何使用它?

我让它在控制器中工作正常.

I have it working just fine in my controllers.

推荐答案

通过一些小的更正,您似乎已经可以使用.您要做的就是将MyAction的实例化实例注入到控制器中,然后您可以使用该实例(而不是尝试使用MyAction类名).

With a few minor corrections, what you've got seems to work already. All you've got to do is inject the guice-instantiated instance of MyAction into your controller, and then you can use the instance (rather than trying to use the MyAction class name).

这适用于Play 2.3:

This works with Play 2.3:

import scala.concurrent.Future
import javax.inject.{Inject, Singleton}
import play.api.mvc._

class UserService() {
  def loadAbc(rh: RequestHeader) = "abc"
}

class MyModel[A](val name: String, request: Request[A]) extends WrappedRequest[A](request)

class MyAction @Inject()(userService: UserService) extends ActionBuilder[MyModel] {
  def invokeBlock[A](request: Request[A], block: (MyModel[A]) => Future[Result]) = {
    val abc = userService.loadAbc(request)
    block(new MyModel(abc, request))
  }
}

@Singleton
class Application @Inject() (myAction: MyAction) extends Controller {
  def index = myAction { request =>
    Ok(request.name)
  }
}

您不能使用object,因为这违反了Guice的设计. object是由Scala本身实例化的单例,并且不能具有实例变量,而Guice需要能够即时实例化类,以便可以注入依赖项.

You can't use object because that violates the design of Guice. object is a singleton instantiated by Scala itself and cannot have instance variables, whereas Guice needs to be able to instantiate classes on the fly so that it can inject dependencies.

这篇关于在游戏中使用ActionBuilder创建自定义动作时使用guice的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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