(Playback 2.4) Injection dependency in symptom?

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

Is there any example?

Thanks.

+7
scala dependency-injection guice playframework
source share
1 answer

I am talking about runtime DI with Guice here because it is the default method used by Play. Other methods or DI frameworks may vary here.

It is not possible to attach a dependency to a trait because the trait is not real. A trait does not have a constructor for defining dependencies.

On Play, you can use the injector directly if Application is in scope. But this is not considered good practice in production code. In the test code, this will 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] } } 
+6
source share

All Articles