Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Play 2.4) Dependency injection in a trait?

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

Is there any example ?

Thanks.

like image 861
Max Avatar asked Aug 10 '15 15:08

Max


1 Answers

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]
  }
}
like image 194
akkie Avatar answered Oct 03 '22 10:10

akkie