Play Framework: Dependency Inject Action Builder

后端 未结 3 1905
猫巷女王i
猫巷女王i 2020-12-14 19:30

since Play Framework 2.4 there is the possibility to use dependency injection (with Guice).

Before I used objects (for example AuthenticationService) in

3条回答
  •  悲&欢浪女
    2020-12-14 20:05

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

提交回复
热议问题