-
-
Save mizchi/9297808 to your computer and use it in GitHub Desktop.
simple inejctor
This file contains hidden or 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
import scala.reflect.{classTag, ClassTag} | |
object Injector { | |
private val rootInjector = new Injector(None) | |
def createInjector = rootInjector.createChild(rootInjector) | |
def mapValue[T:ClassTag](instance:T): Unit = | |
rootInjector.mapValue[T](instance) | |
} | |
class Injector(val parent:Option[Injector]) { | |
private val valueMap = | |
scala.collection.mutable.Map[ClassTag[_], Any]() | |
def clear = valueMap.clear | |
def createChild:Injector = new Injector(Some(this)) | |
def createChild(parent:Injector):Injector = new Injector(Some(parent)) | |
private def hasInjectedValue(cTag:ClassTag[_]):Boolean = { | |
valueMap.get(cTag) match { | |
case Some(_) => true | |
case None => false | |
} | |
} | |
def mapValue[T:ClassTag](instance:T): Unit = { | |
valueMap += classTag[T] -> instance | |
} | |
def getInstance[T:ClassTag]: T = | |
valueMap.get(classTag[T]) match { | |
case Some(i) => i.asInstanceOf[T] | |
case None => { | |
parent match { | |
case Some(j) => j.getInstance[T] | |
case None => throw new Error("no injected target error") | |
} | |
} | |
} | |
} | |
trait Inject { | |
var injector:Injector = Injector.createInjector | |
def injected[T:ClassTag]: T = injector.getInstance[T] | |
} | |
trait CustomInject { | |
val injector:Injector | |
def injected[T:ClassTag]: T = injector.getInstance[T] | |
} | |
//How to use | |
class A(val x:Int) | |
class B | |
class C extends Inject { | |
val a: A = injected[A] | |
val b: B = injected[B] | |
def run: Unit = println(a.x, b) | |
} | |
Injector.mapValue(new A(4)) | |
Injector.mapValue(new B) | |
val c = new C | |
c.run | |
class D extends CustomInject { | |
val injector = Injector.createInjector | |
val a: A = injected[A] | |
val b: B = injected[B] | |
def run: Unit = println(a.x, b) | |
} | |
val d = new D | |
d.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment