简体   繁体   中英

Can we use Google Guice DI with a Scala Object instead of a Scala class in Play 2.4 with scala

Our application is built on Play 2.4 with Scala 2.11 and Akka . Cache is used heavily in our application.We use Play's default EhCache for caching.

We currently use the Cache object (play.api.cache.Cache) for Caching

import play.api.Play.current
import play.api.cache.Cache

object SampleDAO extends TableQuery(new SampleTable(_)) with SQLWrapper {
  def get(id: String) : Future[Sample] = {
    val cacheKey = // our code to generate a unique cache key
    Cache.getOrElse[Future[[Sample]](cacheKey) {
      db.run(this.filter(_.id === id).result.headOption)
    }
  }
}

Now with Play 2.4 we plan to make use of the inbuilt Google Guice DI support. Below is a sample example provided by the Play 2.4 docs

import play.api.cache._
import play.api.mvc._
import javax.inject.Inject

class Application @Inject() (cache: CacheApi) extends Controller {

}

The above example inserts dependency into a Scala class constructor . But in our code SampleDAO is a Scala object but not class .

So now Is it possible to implement Google Guice DI with A scala object instead of a scala class ?

No, it is not possible to inject objects in guice. Make your SampleDAO a class instead, where you inject CacheApi . Then inject your new DAO class in your controllers. You can additionally annotate SampleDAO with @Singleton . This will ensure SampleDAO will be instantiated only once. The whole thing would look something like this:

DAO

@Singleton
class SampleDAO @Inject()(cache: CacheApi) extends TableQuery(new SampleTable(_)) with SQLWrapper {
  // db and cache stuff
}

Controller

class Application @Inject()(sampleDAO: SampleDAO) extends Controller {
  // controller stuff
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM