How to inject a config instance when instantiating an injected class?

I have a simple situation:

class MyClass @Inject() (configuration: Configuration) {

    val port = configuration.get[String]("port")

    ...

}

      

and now I want to use MyClass in another object:

object Toyota extends Car {

  val myClass = new MyClass(???)

  ...

}

      

but I don't know how when using MyClass I will pass it a config instance that is annotated to be injected when MyClass is created.

im using play2.6 / juice / scala

thank!

+3


source to share


1 answer


First of all, you have to decide if you really want dependency injection. The basic idea behind DI is that instead of the factories themselves or objects creating new objects, you externally pass dependencies and hand off the instantiation problem to someone else.

You assume all of this has to do with it if you rely on the framework, so you can't use it with DI. You cannot pass / inject a class into a scala object, here is a draft of what you can do: new

Play / guice takes some preparation.

Injection module to tell you how to create objects (if you can't do it, if annotations or want to do it in one place).

class InjectionModule extends AbstractModule {
  override def configure() = {
    // ...
    bind(classOf[MyClass])
    bind(classOf[GlobalContext]).asEagerSingleton()
  }
}

      

Insert the injector to access it.

class GlobalContext @Inject()(playInjector: Injector) {
  GlobalContext.injectorRef = playInjector
}

object GlobalContext {
  private var injectorRef: Injector = _

  def injector: Injector = injectorRef
}

      



Indicate which modules to include, because there may be several of them.

// application.conf
play.modules.enabled += "modules.InjectionModule"

      

And finally, the client code.

object Toyota extends Car {

  import GlobalContext.injector

  // at this point Guice figures out how to instantiate MyClass, create and inject all the required dependencies
  val myClass = injector.instanceOf[MyClass]

  ...

}

      

The simple situation is expanded with the help system. So, you should really consider other possibilities. Maybe it would be better to pass configs as an implicit parameter in your case?

For dependency injection with guice take a look at: ScalaDependencyInjection with play and Guice wiki

+2


source







All Articles