How to access Play Framework 2.4 guice Injector in application?

前端 未结 5 1514
予麋鹿
予麋鹿 2021-01-11 21:57

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 Fa

5条回答
  •  Happy的楠姐
    2021-01-11 22:04

    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]
    

提交回复
热议问题