T
T
tasce2016-05-30 18:53:28
Play Framework
tasce, 2016-05-30 18:53:28

How to inject a DB dependency into an object?

I'm studying version 2.5. It's all built on dependency injection, and the documentation hasn't been updated. To work with the database, I use Anorm:

case class User(id: Long, login: String, password: String, email: String )

object User {
def login(email: String, password: String): Option[User] = {
    DB.withConnection { implicit c =>
      // TODO
    }
  }
}

DB used to be a simple object play.api.db.DB, now it's marked with @deprecated "Inject DBApi into your component".
Question: how to inject a dependency into an object? Or it is necessary to change structure of models? I figured out the dependency injection in controllers. And this is where it hit a dead end. Not in the controler to work from a DB.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Artem, 2016-05-30
@tasce

Try like this

class UserApi @Inject() (db:  play.api.db.DBApi ) {
  val dababase = db.database("name")

   def login(email: String, password: String): Option[User] = {
    dababase.withConnection { implicit c =>
      // TODO
     }
    }
}

//controller 

class MyController @Inject() (userApi: UserApi ) extends Conroller {
 //your code
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question