播放框架:Dependecy Inject Action Builder [英] Play Framework: Dependecy Inject Action Builder
问题描述
由于Play Framework 2.4有可能使用依赖注入(使用Guice)。
在我使用对象之前(例如 AuthenticationService
)在我的ActionBuilders中:
对象AuthenticatedAction扩展ActionBuilder [AuthenticatedRequest] {
override def invokeBlock [A](请求:请求[A],块:(AuthenticatedRequest [A])=>未来[结果]):未来[结果] = {
...
AuthenticationService.authenticate(。 ..)
...
}
}
现在 AuthenticationService
不再是一个对象,而是一个类。我如何仍然使用我的 ActionBuilder
中的 AuthenticationService
?
将身份验证服务中的动作构建器定义为抽象字段。然后将它们混合到您的控制器中,您可以向其注入服务。例如:
trait MyActionBuilders {
/ pre>
//抽象依赖关系
def authService:AuthenticationService
def AuthenticatedAction = new ActionBuilder [AuthenticatedRequest] {
override def invokeBlock [A](request:Request [A],block(AuthenticatedRequest [A])=> Future [Result]):Future [结果] = {
authService.authenticate(...)
...
}
}
}
和控制器:
@Singleton
类MyController @Inject()(authService:AuthenticationService)使用MyActionBuilders扩展Controller。{
def myAction(...)= AuthenticatedAction {implicit request =>
Ok(authenticated!)
}
}
since Play Framework 2.4 there is the possibility to use dependency injection (with Guice).
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 (...) ... } }
Now
AuthenticationService
is not an object anymore, but a class. How can I still use theAuthenticationService
in myActionBuilder
?解决方案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(...) ... } } }
and the controller:
@Singleton class MyController @Inject()(authService: AuthenticationService) extends Controller with MyActionBuilders { def myAction(...) = AuthenticatedAction { implicit request => Ok("authenticated!") } }
这篇关于播放框架:Dependecy Inject Action Builder的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!