我想在Akka Actors中使用Guice Dependency Injection。
Akka文档,here,建议使用IndirectActorProducer
进行依赖注入。但它没有解释,或者我不明白,原因。
在我看来,它应该用于避免在Props中传递不可序列化的组件/服务。但是我发现的其他例子(here或here)通过整个Injector
类,我很确定它不可序列化。
所以我的问题是:
IndirectActorProducer
?Props
必须是可序列化的吗?将Guice Injector
作为Props参数传递是好的吗?我知道有类似的问题,但在我看来还没有一个明确的答案:
它可能不是您正在寻找的答案,因此请保持问题公开,以防其他人提供更多基于Guice的答案。
基本上我们使用DI框架/库的原因是因为手动传递参数的开销,也可能是接口实现解耦(尽管后者可以简单地通过在构造函数中传递函数并使用它们来创建实现来解决,所以它不是这很多论点)。
在Scala中,至少在为简单项目而离开Java的代码库中,人们只需将事物作为参数传递:
class MyActor(name: String, surname: String) extends Actor { ... }
def createActor(name: String, surname: String) =
system.actorOf(Props(MyActor.class, name, surname))
不喜欢手动操作的人有一些其他的选择,但大多数是基于编译时反射,例如Macwire使用类型来注入东西:
// tags used to distinguish things - something like named instance in Guice
// but on types instead of strings
sealed trait Name
sealed trait Name
class MyActor(name: String @@ Name,
surname: String @@ Surname) extends Actor { ... }
def createActor(name: String @@ Name, surname: String @@ Surname) =
// wire is a macro that puts arguments into constructor by looking at
// variables in the current scope and their types
system.actorOf(Props(wire[MyActor]))
由于此处链接错误出现在编译时而非运行时期间,因此很多人认为这比Java生态系统提出的解决方案更容易维护。
并且因为只要你的参数是可序列化的,这个宏只是展开到普通的旧参数传递代码,你就没有像unserializable Injector
这样的问题。