Created
May 20, 2011 13:45
-
-
Save aloiscochard/982914 to your computer and use it in GitHub Desktop.
Simple Dependency Injector
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
///////////////////////// | |
// 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