问题
I have a couple of services that I want to inject into akka actors. There are three different types of actors I am working with, and each type will use different services. Currently I just have a module, instantiate an injector inside of the actor, and do the binding inside of each Crow. The issue is that for each other, they receive a new instance of the service.
I did a little bit of reading and found http://www.typesafe.com/activator/template/activator-akka-scala-guice
but the documentation for akka recommends we not use IndirectActorProducer
. What is the best way for me to inject these services into my actors? The @Inject keyword looks promising but I'm not exactly sure how to use this.
Workflow:
Main creates commander, sends it a command, commander creates the three different types of crows, and sends them messages to execute (it is these crows that require the services).
回答1:
In your module use @Provides methods that accept the services as params and return ActorRefs. In these provider methods you instantiate Props from the injected services, but let the akka actually create the actor, so you don't need a child injector.
See my answer to https://stackoverflow.com/a/30901808/1341546 for an example.
回答2:
I ended up using http://www.typesafe.com/activator/template/activator-akka-scala-guice as a guide. I found that it works pretty well, and it doesn't actually use IndirectActorProducer but rather another class extending it, which is what they recommend as well.
来源:https://stackoverflow.com/questions/31755016/injecting-services-into-scala-akka-actors-with-google-guice