在Play 2.3中,我们可以创建一个扩展来为Akka actor依赖注入设置默认注入器。在我们迁移到2.4之后,我们不再需要创建我们的注入器了。我们如何重用Play's injector
来为Akka actor注入依赖?
我们有GuiceExtensionProvider
这样:
/**
* 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)
}
系统启动时,我们会调用这些来初始化扩展名:
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)
这是我们用来初始化演员的方式:Akka.system.actorOf(GuiceExtensionProvider(Akka.system).props(classOf[EmailActor]), "emailActor")
答案 0 :(得分:1)
Play框架有关于此主题的相当好的文档: Play scala/akka dependency injection integration
在父actor上,你只需要使用@Inject并使用AkkaGuiceSupport特性声明一个Guice模块。你可以使用@Named注释注入你的演员。儿童演员有点棘手,你必须使用Guice's assisted inject。