Skip to content

Instantly share code, notes, and snippets.

@aloiscochard
Created May 20, 2011 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aloiscochard/982914 to your computer and use it in GitHub Desktop.
Save aloiscochard/982914 to your computer and use it in GitHub Desktop.
Simple Dependency Injector
/////////////////////////
// Dependency Injector //
/////////////////////////
import scala.collection.immutable.HashMap
object Injector {
private var registry = new HashMap[java.lang.Class[_], Any]
def inject[T : Manifest] : T = {
val from = manifest[T].erasure
registry.get(from).asInstanceOf[Option[T]] match {
case Some(o) => o
case None => throw new RuntimeException("Unable to inject %s: no implementation bound".format(from))
}
}
def bind[T : Manifest](to: AnyRef) : Unit = {
val from = manifest[T].erasure
registry += from -> to
}
}
//////////////////
// Sample usage //
//////////////////
import Injector._
trait UserService {
def create : String
}
class DefaultUserService extends UserService {
override def create = "Alois Cochard"
}
class Collaborator {
private lazy val userService = inject[UserService]
def start() {
println(userService.create)
}
}
bind[UserService](new DefaultUserService)
new Collaborator().start
bind[List[String]](List("hello", "dependecy", "injection", "world"))
println(inject[List[String]].mkString(" "))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment