Play Framework PathBindable with Dependency Injection
A

2

7

I'm migrating a Scala Play application to 2.5 and am currently moving my components to dependency injection. There's one place left where I'm at a loss how to do it though. I have a PathBindable implicit conversion defined in the companion object:

object Task {
  implicit def pathBindable(implicit stringBinder: PathBindable[String]) =
    new PathBindable[Task] {
       ...
    }
}

The implementation of the PathBindable needs to look up the object from a repository, but I haven't found a way to dependency-inject the repository here. As a workaround I'm using the now deprecated Play object:

val tasks = Play.application(Play.current).injector.instanceOf[TasksRepository]

Any ideas how to solve this properly?

Annecorinne answered 5/4, 2016 at 9:31 Comment(0)
A
3

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 and should therefore be fast and not block.

Annecorinne answered 14/4, 2016 at 9:32 Comment(0)
T
0

I think this is the only way you can access stuff like this in objects.

A better idea is to create a the transformer like this:

class TaskPathBinder @Inject() ( tasks : TaskRepository ) extends PathBindable[Task]{
  // implementiation
}

and than inject it in services like this

class NeedsTaskPathBinder @Inject() ( service : SomeSerive ) (implicit taskPathBinder : TaskPathBinder) {

   ... 

}

Hope the you get the idea.

Tsimshian answered 5/4, 2016 at 13:7 Comment(1)
Hm, the problem is that the implicit needs to be available to the routes so that I can use it there: playframework.com/documentation/2.5.x/api/scala/…Annecorinne

© 2022 - 2024 — McMap. All rights reserved.