I was looking for a way to inject dependencies in Scala, sort of like Spring or Unity in C #, and I did not find anything really interesting.
- MacWire: I don’t understand the benefits, because we have to provide the class in the [CASS] explorer. So, what's the point if you give an implementation when you call? I can make a new CASS, it will be the same.
- Drawing a pie with type type: It seems to not respond to what I'm looking for.
So, I decided to make my implementation and ask you what you think, because it surprised me that nothing like this had been done before. Perhaps in my implementation there are many problems in real life.
So here is an example:
trait Messenger {
def send
}
class SkypeMessenger extends Messenger {
def send = println("Skype")
}
class ViberMessenger extends Messenger {
def send = println("Viber")
}
I want an application that is configured in only one place everywhere to be implemented here:
object App {
val messenger = Inject[Messenger]
def main(args: Array[String]) {
messenger.send
}
}
Inject [Messenger], , , , (prod dev):
object Inject extends Injector with DevConfig
trait ProdConfig {
this: Injector =>
register[Messager](new SkypeMessager)
register[Messager](new ViberMessager, "viber")
}
trait DevConfig {
this: Injector =>
register[Messager](new ViberMessager)
register[Messager](new ViberMessager, "viber")
}
, , , :
class Injector {
var map = Map[String, Any]()
def apply[T: ClassTag] =
map(classTag[T].toString).asInstanceOf[T]
def apply[T: ClassTag](id: String) =
map(classTag[T].toString + id).asInstanceOf[T]
def register[T: ClassTag](instance: T, id: String = "") = {
map += (classTag[T].toString + id -> instance)
instance
}
}
:
- , / ( ) .
- config (dev, prod...), . .
- Config, .
- - apply, ( id), .
?