Skip to content
laforge49 edited this page Oct 28, 2011 · 16 revisions

Dependency Injection (DI) or Injection Of Control (IOC) is done with a composite actor. This actor is created using the SystemServices companion object with one parameter, a component factory.

val systemServices = SystemServices(rootComponentFactory)

Here's the code.

object SystemServices {
  def apply(rootComponentFactory: ComponentFactory, 
            factoryId: FactoryId = new FactoryId("System"),
            properties: Properties = null,
            actorClass: Class[_ <: Actor] = classOf[Actor],
            newMailbox: Mailbox = new ReactorMailbox) = {
    val systemServicesFactory = new CompositeFactory(factoryId, rootComponentFactory, actorClass)
    SetProperties(systemServicesFactory, properties)
    val systemServices = systemServicesFactory.newActor(newMailbox)
    systemServices.setSystemServices(systemServices)
    systemServices._open
    systemServices
  }
}

The SystemServices companion object forces the SystemServices object to call open on its components by calling _open instead of sending it a message.

The SystemServices actor is injected directly into an actor by calling actor.setSystemServices(systemServices). Now lets build a SystemServices actor which offers a single, very simple service.

case class Today()

class Sayings(actor: Actor) 
  extends Component(actor){
  bind(classOf[Today], today)
  def today(msg: AnyRef, rf: Any => Unit) {rf("Today is the first day of the rest of your life.")}
}

class SayingsFactory extends ComponentFactory {
  override protected def instantiate(actor: Actor) = new Sayings(actor)
}

val systemServices = SystemServices(new SayingsFactory)

Now we can create an actor which uses this service and inject it with our SystemServices actor.

case class SaySomething()

class SayIt extends Actor {
  setMainbox(new ReactorMailbox)
  bind(classOf[SaySomething], saySomething)
  def saySomething(msg: AnyRef, rf: Any => Unit) {
    systemServices(Today())(rf)
  }
}

val sayIt = new SayIt
sayIt.setSystemServices(systemServices)

The test code is about as simple as it can get.

println(Future(sayIt, SaySomething()))

Finally, here's the output.

Today is the first day of the rest of your life.

IOCTest

Tutorial

Clone this wiki locally