简体   繁体   中英

(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.

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]
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM