【问题标题】:How to create a dependent Guice (Play / Scala) binding?如何创建依赖的 Guice (Play / Scala) 绑定?
【发布时间】:2023-03-04 22:00:02
【问题描述】:

我正在使用 Scala + Play 和开箱即用的 Guice 设置依赖注入。我还在幕后使用 Akka Persistence,并希望为自定义读取日志创建绑定,然后我可以将其注入到我的应用程序中。

不幸的是,读取日志构造函数(我无法控制)需要对参与者系统的显式引用:

PersistenceQuery(actorSystem).readJournalFor[CustomReadJournal]("custom-key")

如何从绑定定义类 (Module) 中获取对底层 actorSystem 的引用?这可能吗?更一般地说,是否可以定义相互依赖的绑定(a la Scaldi?)

我的Module 类条目目前看起来像:

bind(classOf[CustomReadJournal]).toInstance(PersistenceQuery(<what do i put here?>).readJournalFor[CustomReadJournal]("custom-journal"))

提前感谢您的帮助!

【问题讨论】:

  • 您是否考虑过使用@Provides 并提供您的actorSystem 作为参数以便您也可以注入它?如果需要另外提供,可以通过play.api.libs.concurrent.Akka.system(Play.current)使用play内置的akka​​系统

标签: scala playframework dependency-injection akka guice


【解决方案1】:

如果您需要执行某种逻辑来创建依赖注入,则使用 @Provides 注释很有用。例如:

trait MyProvider {
  @Provides
  def provideThing(): Thing = {
    //make the thing and return it
  }
}
class MyModule extends AbstractModule with MyProvider {
   override def configure() {
     bind(classOf[TraitYYY]).to(classOf[ClassThatTakesThingAsParameter])
   }
}

要知道的一件有用的事情是@Provides 方法本身可以接受参数并注入它们的参数。例如:

@Provides
def provideThingNeedingParameter(param: P): ThingNeedingParam = {
   new ThingNeedingParam(param)
}

我相信这与您的情况有关,因为您想为某个类的实例提供一个演员系统。

// You can use @Singleton with @Provides if you need this to be one as well!
@Provides
def provideActorSystem(app: Application): ActorSystem = {
    play.api.libs.concurrent.Akka.system(app)
}

@Provides
def providePersistenceQuery(actorSystem: ActorSystem): PersistenceQuery = {
    PersistenceQuery(actorSystem)
}

@Provides 
def provideCustomReadJournal(persistenceQuery: PersistenceQuery):CustomReadJournal = {
    persistenceQuery.readJournalFor[CustomReadJournal]("custom-key")    
}

通过为您的 CustomReadJournal 创建一个 @Provides 注释方法,您可以完全避免从 configure 调用 bind 并更多地控制参数。此外,如果您需要,@Provides 可以与@Singleton 一起使用。我没有使用过 Akka 持久化,但我认为这应该对你有所帮助

【讨论】:

    猜你喜欢
    • 2019-06-06
    • 2019-08-16
    • 1970-01-01
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-20
    相关资源
    最近更新 更多