Skip to content

Instantly share code, notes, and snippets.

@aloiscochard
Last active September 11, 2016 16:02
Show Gist options
  • Save aloiscochard/63fba803c379252de333 to your computer and use it in GitHub Desktop.
Save aloiscochard/63fba803c379252de333 to your computer and use it in GitHub Desktop.
Dependency Injection in Scala without Cake Pattern
package com.acme
import com.typesafe.config.Config
trait Module {
implicit def config: Config
}
package com.acme
trait PersistenceModule extends Module {
implicit lazy val postgreSQL = postgresql.Database.fromConfig
implicit lazy val mongoDB = mongo.Database.fromConfig
}
package com.acme
package postgresql
class Database(serverAddr: SocketAddress, val discriminator: Option[String])(implicit config: Config) extends DDL {
...
}
object Database {
def fromConfig(implicit config: Config): Database =
new Database(config(ConfigKeys.ServerAddress), None)
}
package com.acme
class Foo(
implicit postgreSQL: postgresql.Database, mongoDB: mongo.Database, config: Config
) extends Controller with Logging {
...
}
object Global extends GlobalSettings with PersistenceModule with Logging {
override implicit def config: Config = Play.current.configuration.underlying
lazy val foo = new Foo
lazy val bar = new Bar
override def getControllerInstance[A](clazz: Class[A]): A = {
def bind[T](value: T)(implicit ct: ClassTag[T]): Option[A] =
if (clazz == ct.runtimeClass) Some(value.asInstanceOf[A]) else None
val instance =
bind(foo) orElse
bind(bar)
instance.getOrElse(sys.error("Unable to instantiate controller of type: $clazz"))
}
}
object InitializePlatform extends App with PersistenceModule {
override implicit val config = ConfigFactory.load
postgreSQL.init
mongoDB.init
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment