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]
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With