I really like Devabc's solution because there definitely are some scenarios that can't rely on constructor injection to get the injector itself, however in Play 2.5.x you have to use the the deprecated play.api.Play.current.Injector
code to get the injectorinstance.
His solution create a reference to the Play build-in injector and put it into a Scala object which can be imported by any components when they need it. Brilliant!
In order to make it work, however, the object needs to provide a public interface to get the injector, so here is my amended code to fix it and demo of how it can be used.
# GolbalContext.scala
import play.api.inject.Injector
import javax.inject.Inject
@Singleton
class GlobalContext @Inject()(playBuiltinInjector: Injector) {
GlobalContext.injectorRef = playBuiltinInjector
}
object GlobalContext {
private var injectorRef: Injector = _
def injector: Injector = injectorRef
}
The initialization part is the same.
# InjectionModule.scala
package modules
class InjectionModule extends AbstractModule {
override def configure() = {
// ...
// Eager initialize Context singleton
bind(classOf[GlobalContext]).asEagerSingleton()
}
}
Then in the application.conf
, make sure the InjectionModule
is the first module being enabled so the following modules can use the injector properly.
play.modules.enabled += "modules.InjectionModule"
And the client code is quite simple. In whichever component requires the injector:
// Import the object GlobalContext
import GlobalContext.injector
// ...
val yourClassInstance = injector.instanceOf[YourClass]
Play.current
since it will be removed at some point. Maybe you can inject the injector? – Debose