Guicing up Akka Actors
As we mentioned before, we use Guice with Play! Framework for dependency injection. Guice helps us enjoy simpler and faster development and testing.
We’re also heavy users of Akka’s Actors. Here’s how we use them with Play! and Guice and why:
- We instantiate top-level Actors only in a ActorSystem and Props context, even though they may have nontrivial constructors.
- We don’t want to have more than one Actor instance around, since we use them in single-thread mode. Since we dislike using global singletons for testability reasons and since Actors need to have everything injected into them (e.g. HTTP clients, database connections), we annotate ActorInstance with @Singleton and have Guice create the Actors.
- Actors should be able to be re-instantiate on failure, so they are not singletons.
- Testing, i.e. using TestActorRef and not having a big list of Singletons of the ActorRefs there
- Error handling
We introduce two abstractions (ActorInstance and ActorBuilder) to solve the first three issues; the latter two will be discussed in future blog posts.
Note that the code above is for Akka 2.1. When we upgrade to Play 2.2 and Akka 2.2, it will change a bit and use IndirectActorProducer. The general structure won’t change much.
A typical Actor implementation:
The ActorInstance is injected by Guice and ensures that we’ll have a singleton ActorRef but still reconstruct the Actor instance on restarts using the Guice default provider, with all constructor arguments automatically injected.
edit 2013–08–16: We had originally incorrectly described Singleton usage with Actors and ActorRefs. Roland Kuhn provided some great feedback, and the post has been corrected.
Originally published at eng.kifi.com on August 15, 2013.