【发布时间】:2025-05-28 15:35:01
【问题描述】:
play framework doc (https://www.playframework.com/documentation/2.6.x/ScalaAkka) 中有一个例子,解释了如何将actor(需要注入的依赖项)注入控制器:
@Singleton
class Application @Inject()
(@Named("configured-actor") configuredActor: ActorRef)
(implicit ec: ExecutionContext) extends Controller {
implicit val timeout: Timeout = 5.seconds
def getConfig = Action.async {
(configuredActor ? GetConfig).mapTo[String].map { message =>
Ok(message)
}
}
}
但据我了解,它创建了一个演员的单个实例(例如,单例)。
我需要在控制器内创建多个configuredActor 实例。
还有一个示例演示了如何从父actor创建子actor(需要注入依赖项)实例
object ParentActor {
case class GetChild(key: String)
}
class ParentActor @Inject() (
childFactory: ConfiguredChildActor.Factory
) extends Actor with InjectedActorSupport {
import ParentActor._
def receive = {
case GetChild(key: String) =>
val child: ActorRef = injectedChild(childFactory(key), key)
sender() ! child
}
}
我尝试在控制器中应用这种技术,但 injectedChild(childFactory(key), key) 需要(隐式)actor 上下文
def injectedChild(create: => Actor, name: String, props: Props => Props = identity)(implicit context: ActorContext): ActorRef = ...
但我需要从 ActorSysem 创建这个演员(例如 /user)。
(我想得到/user actor 的上下文,但是怎么做?对吗?)
使用 Guice 在父 Actor 之外(例如,在控制器内部)创建多个 Actor 实例的正确方法是什么?
【问题讨论】:
标签: dependency-injection playframework-2.0 akka guice