Reputation: 1108
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 ?
Upvotes: 3
Views: 1470
Reputation: 5699
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
}
Upvotes: 2