Bhavya Latha Bandaru
Bhavya Latha Bandaru

Reputation: 1108

Play with scala - Injecting dependencies through an instance of Guice Injector

My application makes use of Play-2.4.2/Scala-2.11.6 that comes with built-in Guice support for DI

All my DAOs bind an implementation to an interface as below , which is supposed to be the simplest way in Guice

@ImplementedBy(classOf[PersonDAOImpl])
trait PersonDAO {
}

class PersonDAOImpl @Inject()
(
(@NamedDatabase("mysql")protected val dbConfigProvider: DatabaseConfigProvider,
 protected val cache : CacheApi) extends PersonDAO with SQLWrapper {
..
...

}

The above implementation does not need addition of any module to provide bindings.

Now for some reason, I do not want to inject the dependencies into the constructor of Books class using @Inject annotation . So , I tried injecting it as below

class Books {

  val injector = Guice.createInjector()

  val personDAO : PersonDAO = injector.getInstance(classOf[PersonDAOImpl])

..
...

}

But this throws me a guice configuration exception saying :

Caused by: com.google.inject.ConfigurationException: Guice configuration errors:

1) No implementation for play.api.cache.CacheApi was bound.
  while locating play.api.cache.CacheApi
    for parameter 1 at schema.PersonDAOImpl.<init>
  while locating PersonDAO

2)  No implementation for play.api.db.slick.DatabaseConfigProvider annotated with @play.db.NamedDatabase(value=mysql) was bound.
  while locating play.api.cache.CacheApi
    for parameter 2 at schema.PersonDAOImpl.<init>  while locating PersonDAO

What needs to be done now ? Is my approach right or wrong in this case ? Can someone help me out with this ? Thanks in advance.

Upvotes: 2

Views: 2875

Answers (1)

cchantep
cchantep

Reputation: 9168

You can use the Injector from the current Play Application.

import play.api.{ Application, Play }
import play.api.inject.Injector

val currentApp: Application = Play.current
val injector: Injector = currentApp.injector
// in short play.api.Play.current.injector

// Then use the injector
import play.api.inject.ApplicationLifecycle
current.injector.instanceOf[ApplicationLifecycle].
  addStopHook { () => ??? }

(See example using injector with the Play plugin for ReactiveMongo)

Upvotes: 3

Related Questions