Search code examples
scaladependency-injectionguiceplayframework-2.4named

Trying to instantiate named(annotated) classes


First of all, thanks for any effort to try and answer the question. From the current application injector (play.api.Play.current.injector), how do I get a Named instance of a class? I tried to cast the injector to a ScalaInjector (net.codingwell.scalaguice.InjectorExtensions.ScalaInjector) and to Guice Injector (com.google.inject.Injector), both unsuccessful. The problem is that there are only 3 methods to instantiate a class, all of them are overloaded instanceOf[T]


Solution

  • For a normal dependency you would do

    play.api.Play.current.injector.instanceOf[ProjectRepo]
    

    When you want to retrieve a named dependency you can do

    val qualifier = Some(QualifierInstance(Names.named("name")))
    val bindingKey = BindingKey[ProjectRepo](Class[ProjectRepo], qualifier)
    
    play.api.Play.current.injector.instanceOf[ProjectRepo](bindingKey)
    

    Anyway you should only use the injector directly in very rare cases, makes sure there is not a simpler way to retrieve your dependencies.