3
votes

Is it possible to create an akka actor that has implicits in the constructor? Having:

class Actor(parameter: Long)(implicit service:Service)

and

class Service

can I use the context to create the actor like this?

implicit val service:Service = new Service()
val someLong = 3
context.actorOf(FromConfig.props(Props(classOf[Actor], someLong)), "actor")

As a mention the service cannot be passed to the constructor because multiple different actor classes can be received, which use different implicits from the scope.

1

1 Answers

14
votes

Define your Props in Companion object of Actor and is good for injecting Dependencies.

class SomeActor(parameter: Long)(implicit service:Service) extends Actor {
    def receive = {
         case message => // Do your stuff
      }
}

object SomeActor {
   def props(parameter: Long)(implicit service:Service) = Props(new SomeActor(parameter))
}

implicit val service:Service = new Service()
val someLong = 3
val ref = context.actorOf(SomeActor.props(someLong)), "actor")

and you can read more about Dependency Injection here : http://doc.akka.io/docs/akka/snapshot/scala/actors.html#Dependency_Injection http://letitcrash.com/post/55958814293/akka-dependency-injection