Play 框架:依赖注入动作生成器 [英] Play Framework: Dependency Inject Action Builder
问题描述
从 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!")
}
}
这篇关于Play 框架:依赖注入动作生成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!