7

In play 2.4, is it possible to use dependency injection in a trait ?

Is there any example ?

Thanks.

1 Answer 1

6

I talk about runtime DI with Guice here because it's the default method used by Play. Other DI methods or frameworks may differ here.

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.

In Play you could use the injector directly as long as the Application trait is in scope. But this isn't considered good practice in production code. In test code this would be an option.

class MySpec extends PlaySpecification {
  "My test" should {
    "Use the injector" in new WithApplication extends Context {
      val messages = Messages(Lang("en-US"), messagesApi)
    } 
  }

  trait Context extends Scope {
    self: WithApplication =>

    val messagesApi = app.injector.instanceOf[MessagesApi]
  }
}
1
  • 7
    So in production code, what is the good, recommended way, for example when you need to use "AuthService" in a "Secured" trait: stackoverflow.com/q/34223440/56285
    – Jonik
    Dec 11, 2015 at 12:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.