TheDarkSaint
TheDarkSaint

Reputation: 457

Play framework inherit dependency injected trait?

Is it possible to create an overloaded play.api.mvc.Controller trait that has dependency injected arguments?

For example, say I have a couple of customized Actions that require a dependency injected AuthorizationService. I would like to write my controllers like this:

class UserController extends CustomController {
  def getUser(userID: String) = CustomAction {
    ...
  }
}

However, I can't figure out how to create the CustomController trait such that it doesn't require me to inject my AuthorizationService in my UserController. Is there a way to do this with Guice?

Upvotes: 1

Views: 1627

Answers (2)

yahor
yahor

Reputation: 401

You can inject a field into your CustomController trait. The field should'n be final so it has to be declared as var in Scala.

@Inject() var authService: AuthorizationService

You can also make the injected var private and declare a public val which references the injected field. In this case val has to be lazy since injection occurs after class was instantiated. See Guice docs for more details.

@Inject() private var as: AuthorizationService = _
lazy val authService: AuthorizationService = as

Upvotes: 5

mgosk
mgosk

Reputation: 1876

It isn't possible to inject a dependency into a trait because a trait isn't instantiable. A trait doesn't have a constructor to define the dependencies, you must inject your AuthService via UserController

Example.

trait CustomController extends Controller {
  val authService: AuthService
  ...
}

class UserController @Inject()(override val authService: AuthService) extends CustomController {
  ...
}

Upvotes: 1

Related Questions