【问题标题】:Play 2.4 dependency injection in Akka actors在 Akka actor 中玩 2.4 依赖注入
【发布时间】:2015-12-18 23:02:41
【问题描述】:

在 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")

【问题讨论】:

    标签: scala playframework akka playframework-2.3 playframework-2.4


    【解决方案1】:

    Play 框架有一个关于这个主题的很好的文档: Play scala/akka dependency injection integration

    在父 Actor 上,您只需要使用 @Inject 并声明一个具有 AkkaGuiceSupport 特征的 Guice 模块。比你可以使用 @Named 注释注入你的演员。儿童演员有点棘手,你必须使用Guice's assisted inject

    【讨论】:

      猜你喜欢
      • 2015-12-16
      • 2016-02-26
      • 1970-01-01
      • 2015-10-08
      • 2017-01-31
      • 1970-01-01
      • 2014-01-19
      • 2015-11-02
      • 1970-01-01
      相关资源
      最近更新 更多