I want to use the getInstance
method of the Guice Injector
class in Play Framework 2.4, how can I access it?
I have used the Guice FactoryModuleBuilder
for implementing a factory that returns another factory at runtime! At the second level of returning a factory I need to access the Play Guice Injector to get objects manually using reflection instead of @Inject
annotation.
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
}