[scaldi-play 0.5.8] Binding ReactiveMongo in Play 2.4

58 views
Skip to first unread message

Neil Chaudhuri

unread,
Sep 13, 2015, 11:09:55 AM9/13/15
to scaldi
I have a MongoDB uri configured in application.conf, and I would like to initialize and bind my ReactiveMongo database on application startup. My question is if it is even possible to inject configuration information into my module. In other words, does the Play integration fetch all the  default Play bindings first to then allow me access to the Configuration in a module where I can then set up more eager bindings on startup?

Here is my binding with the desired config bolded and enlarged to an absurd degree:

bind[DB] identifiedBy 'db toNonLazy {
val driver = new reactivemongo.api.MongoDriver
val dbT: Try[DB] = MongoConnection.parseURI(uri).map { parsedUri =>
val connection = driver.connection(parsedUri)
connection.db(parsedUri.db.get)
}
dbT
match {
case Success(db) => db
case Failure(ex) => throw new RuntimeException(ex)
}
}







Oleg Ilyenko

unread,
Sep 14, 2015, 4:27:40 AM9/14/15
to scaldi
Sure, it is possible. Let's say the property is called "mongodb.uri". It it's just a single uri, you can just inject it as a `String` like this:

val uri = inject [String] ("mongodb.uri")

If it's a list of URIs, the it should be something like this:

val uri = inject [List[String]] ("mongodb.uri")

You can find more info about this feature in the documentation:

Neil Chaudhuri

unread,
Sep 14, 2015, 10:14:34 AM9/14/15
to scaldi
I ended up solving it this way:

bind[DB] identifiedBy 'db toNonLazy {
val driver = new reactivemongo.api.MongoDriver
  val dbT: Try[DB] = MongoConnection.parseURI(inject[String](identified by "mongodb.uri")).map { parsedUri =>

val connection = driver.connection(parsedUri)
connection.db(parsedUri.db.get)
}
dbT match {
case Success(db) => db
case Failure(ex) => throw new RuntimeException(ex)
}
}


What is the difference between my identifiedBy approach and yours?

Thanks.

Oleg Ilyenko

unread,
Sep 14, 2015, 4:01:45 PM9/14/15
to scaldi
Great! The approach I described is exactly the same. `inject [Foo] ("bar")` is a shortcut and equivalent of `inject [Foo] (identified by "bar")`.

Neil Chaudhuri

unread,
Sep 16, 2015, 3:40:40 PM9/16/15
to scaldi
Just in case anyone sees this thread in the future, it turns out that my solution, while it seems to work, is unnecessary. It turns out ReactiveMongo provides a module to facilitate direct injection, which means you can use it with Scaldi in the usual way:

lazy val reactiveMongoApi = inject[ReactiveMongoApi]
def collection = reactiveMongoApi.db.collection[BSONCollection]("collectionName")

Hope that helps anyone using Scaldi and ReactiveMongo in a Play 2.4.x application.
Reply all
Reply to author
Forward
0 new messages