Scala dependency injection

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), .

?

+3
3

- Lift. Lift, , . "", . doc. Lift:

package net.liftweb.http

/**
 * A base trait for a Factory.  A Factory is both an Injector and
 * a collection of FactorMaker instances.  The FactoryMaker instances auto-register
 * with the Injector.  This provides both concrete Maker/Vender functionality as
 * well as Injector functionality.
 */
trait Factory extends SimpleInjector

: Scala - /, / , , Lift .

+2

MacWire, , new - :). MacWire - , ( ).

The basic idea is that you are wiring at the end of the world where you build your application (or you can split it into trait modules, but this is optional). Otherwise, you simply use constructors to express dependencies. No magic, no frameworks.

0
source

All Articles