I have problems understanding the basic idea of dependency injection. (I am using Play 2.5 with the play-slick module). I have a Users class that needs to connect to a database.
package models @Singleton class Users @Inject() (dbConfigProvider: DatabaseConfigProvider) { private val db = dbConfigProvider.get[JdbcProfile].db private val users = TableQuery[UserTable] private val setupAction = DBIO.seq(users.schema.create) private val setupFuture: Future[Unit] = db.run(setupAction) def getAll(): Future[Seq[User]] = setupFuture.flatMap(_ => db.run(users.result) ) // More methods like the previous }
When I have a view that should access these methods, I expect the dependency injection system to fill in a dbConfigProvider dependency for me like this.
package views class UserSearch { def index(implicit ec: ExecutionContext): Future[String] = Future( (new Users).getAll().map(seq => seq.map(user => user.name).mkString(" ")) ) }
However, this gives me a compilation error, and I am forced to make the dbConfigProvider dependency of my view and pass it explicitly. In this case, I finally get dbConfigProvider from the controller calling the view.
package views class UserSearch @Inject (dbConfigProvider: DatabaseConfigProvider) { def index(implicit ec: ExecutionContext): Future[String] = Future( (new Users(dbConfigProvider)).getAll().map(seq => seq.map(user => user.name).mkString(" ")) ) }
I guess I misunderstood how dependency injection should work.
So my questions are these:
What is the use of the @Inject() keyword in my Users model, then?
Is my project a failure? I would like the Users and UserSearch objects to be objects, but then I cannot use dependency injection on them.
In case anyone is familiar with Slick, is my getAll() method used to work with slick? Is this even the right way to write asynchronous code?
scala dependency-injection playframework slick
rusins
source share