fxlae
fxlae

Reputation: 905

Guice in Scala: Module for a class that has a DI-constructor itself

I'm using codingwell/scala-guice and trying to inject DAO-classes into constructors of other components/classes.

In the first attempt, I only used one DAO-class to see if it works:

class DaoModule extends AbstractModule with ScalaModule {
  override def configure() {
    val dao1 = new FirstDaoImpl
    bind(new TypeLiteral[FirstDaoTrait] {}).toInstance(dao1)
  }
}

The binding works as expected, it can be used for constructor injection.

In the second step, I wanted to add another DAO class to the module. However, that DAO-class depends on the first DAO:

class SecondDaoImpl @Inject()(firstDao: FirstDaoTrait) extends SecondDaoTrait

I'm not sure how to add the necessary binding to the existing module. Repeating the first step would result in this:

val dao2 = new SecondDaoImpl(???)
bind(new TypeLiteral[SecondDaoTrait] {}).toInstance(dao2)

But of course this class can only be instantiated by providing the first DAO (therefore the "???"). How can I do this?

Upvotes: 2

Views: 1134

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149538

Use bind and let scala-guice resolve the dependencies for you:

class DaoModule extends AbstractModule with ScalaModule {
  override def configure() {
    bind[FirstDaoTrait].to[FirstDaoImpl]
    bind[SecondDaoTrait].to[SecondDaoImpl]
  }
}

And now using the injector:

val injector = Guice.createInjector(new DaoModule())
val secondDao = injector.instance[SecondDaoTrait]

Upvotes: 2

Related Questions