Play Framework PathBindable 与依赖注入
Play Framework PathBindable with Dependency Injection
我正在将 Scala Play 应用程序迁移到 2.5,目前正在将我的组件移动到依赖项注入。不过,还有一个地方让我不知所措。我在伴随对象中定义了一个 PathBindable 隐式转换:
object Task {
implicit def pathBindable(implicit stringBinder: PathBindable[String]) =
new PathBindable[Task] {
...
}
}
PathBindable 的实现需要从存储库中查找对象,但我还没有找到依赖注入存储库的方法。作为解决方法,我使用现在已弃用的 Play 对象:
val tasks = Play.application(Play.current).injector.instanceOf[TasksRepository]
有什么办法可以正确解决这个问题吗?
我认为这是您可以在对象中访问此类内容的唯一方法。
一个更好的主意是像这样创建一个转换器:
class TaskPathBinder @Inject() ( tasks : TaskRepository ) extends PathBindable[Task]{
// implementiation
}
然后像这样将其注入服务
class NeedsTaskPathBinder @Inject() ( service : SomeSerive ) (implicit taskPathBinder : TaskPathBinder) {
...
}
希望你明白了。
According to Lightbend Engineer Greg Methvin, PathBindables should only depend on the state in the path. The reason is that the code runs on the IO thread 因此应该很快而不是阻塞。
我正在将 Scala Play 应用程序迁移到 2.5,目前正在将我的组件移动到依赖项注入。不过,还有一个地方让我不知所措。我在伴随对象中定义了一个 PathBindable 隐式转换:
object Task {
implicit def pathBindable(implicit stringBinder: PathBindable[String]) =
new PathBindable[Task] {
...
}
}
PathBindable 的实现需要从存储库中查找对象,但我还没有找到依赖注入存储库的方法。作为解决方法,我使用现在已弃用的 Play 对象:
val tasks = Play.application(Play.current).injector.instanceOf[TasksRepository]
有什么办法可以正确解决这个问题吗?
我认为这是您可以在对象中访问此类内容的唯一方法。
一个更好的主意是像这样创建一个转换器:
class TaskPathBinder @Inject() ( tasks : TaskRepository ) extends PathBindable[Task]{
// implementiation
}
然后像这样将其注入服务
class NeedsTaskPathBinder @Inject() ( service : SomeSerive ) (implicit taskPathBinder : TaskPathBinder) {
...
}
希望你明白了。
According to Lightbend Engineer Greg Methvin, PathBindables should only depend on the state in the path. The reason is that the code runs on the IO thread 因此应该很快而不是阻塞。