How to access Play Framework 2.4 guice Injector in application?
There are many ways. I use this one.
Edit: This is relevant for Play versions which are <= 2.4:
Play.maybeApplication.map(_.injector.instanceOf[MyProdClass]).getOrElse(new MyDevClass)
or
Play.current.injector.instanceOf[MyClass]
For versions which are >= 2.5:
import play.api.inject.Injector
import javax.inject.Inject
class MyService @Inject() (injector: Injector) ={
val myClassInstance = injector.instanceOf[MyClass]
//do stuff
}
With Play Framework 2.5.x play.api.Play.current
is deprecated and DI should always be preferred. Therefore proper way of getting injector instance is by using:
import play.api.inject.Injector
import javax.inject.Inject
class SomeClassRequiringInjector @Inject() (injector: Injector) { ... }
Works for me even when doing this with DI Provider class :)