DB and compile time dependency injection

236 views
Skip to first unread message

Ronald Cirka

unread,
Jun 9, 2015, 2:14:56 PM6/9/15
to play-fr...@googlegroups.com
I am trying to use Slick 3.0 with Macwire. When extending BuiltInComponentsFromContext, I am not able to use

lazy val db = Database.forDataSource(DB.getDataSource())

since DB.getDataSource() requires an implicit application, and the application has not started yet. (passing in the application from BuiltInComponentsFromContext will cause play to hang on load)

I am guessing the new idiomatic to load components is for the component to have a reference to ApplicationLifecycle, instead of Application - for example the NingWSAPI in Play 2.4 uses ApplicationLifecycle. However, none of the DB interfaces appear to have a reference ApplicationLifecycle; the BoneCPPlugin also expects Application, not ApplicationLifecycle. Am I missing something, or is the DB Api not suited for compile time injection?

Ronald Cirka

unread,
Jun 9, 2015, 5:02:39 PM6/9/15
to play-fr...@googlegroups.com
Never mind i figured it out. I needed to mix in the trait DBComponents.

trait DBModule extends DBComponents {
  def dbApi: DBApi
  lazy val connectionPool: ConnectionPool = wire[BoneConnectionPool]
  lazy val db = Database.forDataSource(dbApi.database("default").dataSource)
}

app.conf:
db.default.driver=org.postgresql.Driver
db.default.url=...

Loic

unread,
Aug 31, 2015, 5:14:19 AM8/31/15
to play-framework
I have the same problem, with Anorm, that does not provide Database.forDataSource method.
Do you know how to to instantiate the DB API? I did not find any example to do this.

My application loader is define as : 


class SimpleApplicationLoader extends ApplicationLoader {
  def load(context: Context) = {
    new ApplicationComponents(context).application
  }
}

trait DBModule extends DBComponents with HikariCPComponent {
  def dbApi: DBApi
  //lazy val db = ??
}

class ApplicationComponents(context: Context) extends BuiltInComponentsFromContext(context) with DBComponents {       
  lazy val applicationController = new controllers.Application("test")
  lazy val assets = new controllers.Assets(httpErrorHandler)
  override lazy val router = new Routes(httpErrorHandler, applicationController, assets)
}}

When I'm trying to use the DB with ;

DB.withConnection { implicit connection =>
    // ...
    }

I have this error : 
java.lang.NoSuchMethodException: play.api.db.DBApi.<init>()

Thanks :)

Loic

unread,
Aug 31, 2015, 8:26:04 AM8/31/15
to play-framework
It seems that I just need to remove DB object and create one from the dbApi instead. 

val db = dbApi.database("default")

I don't know why I was thinking DB.withconnection was using the injector under the hood...  :)
Reply all
Reply to author
Forward
0 new messages