Reputation: 9428
In Play 2.3, we can create an extension to set default injector for Akka actor dependency injection. After we migrated to 2.4, we don't need to create our injector anymore. How can we reuse Play's injector
to inject dependencies to Akka actor?
We have a GuiceExtensionProvider
like this:
/**
* An Akka Extension Provider
*/
object GuiceExtensionProvider extends ExtensionId[GuiceExtension] with ExtensionIdProvider {
override def lookup = GuiceExtensionProvider
/**
* Is used by Akka to instantiate the Extension identified by this ExtensionId, internal use only.
*/
override def createExtension(system: ExtendedActorSystem): GuiceExtension = new GuiceExtension(system)
}
/**
* The Extension implementation.
*/
class GuiceExtension(system: ExtendedActorSystem) extends Extension {
private var injector: Injector = _
/**
* Used to initialize the Guice Injector for the extension.
*/
def initialize(injector: Injector) = this.injector = injector
/**
* Create a Props for the specified actorType using the GuiceActorProducer class.
*
* @param actorType The type of the actor to create Props for
* @return a Props that will create the typed actor bean using Guice
*/
def props(actorType: Type): Props = Props(classOf[GuiceActorProducer], injector, actorType)
}
When the system starts, we will call these to initialize the extension:
class MyModule extends ScalaModule {
def configure() {
}
}
val injector = Guice.createInjector(new MyModule()) <--- `How can we use the default injector from Play?`
GuiceExtensionProvider(Akka.system).initialize(injector)
This is how we used to initialize an actor: Akka.system.actorOf(GuiceExtensionProvider(Akka.system).props(classOf[EmailActor]), "emailActor")
Upvotes: 2
Views: 2752
Reputation: 123
Play framework has a pretty good documentation on this topic: Play scala/akka dependency injection integration
On parent actors, you just need to use @Inject and declare a Guice module with AkkaGuiceSupport trait. Than you can inject your actors using @Named annotation. Child actors is bit tricky, you must use Guice's assisted inject.
Upvotes: 1