Play 2.1 getControllerInstance usage?

2019-07-18 11:05发布

What is the intended usage pattern for getControllerInstance on GlobalSettings? Is it possible to use it without a dependency injection framework?

the signature is getControllerInstance[A](controllerClass: Class[A]): A

So, from what I understand, this gets called on any route that is specified with the @ prefix, and you must return an instance of that type of controller (A). But if A is the parameterized type of Class it is subject to type erasure at runtime, correct? How can I know which controller class is being asked for?

1条回答
Luminary・发光体
2楼-- · 2019-07-18 11:44

I found the way that looks very non-Scala, but works for me.

override def getControllerInstance[A](controllerClass: Class[A]): A = {
  if (controllerClass == classOf[CardsService]) ComponentsRegistry.cardsService.asInstanceOf[A]
  else super.getControllerInstance(controllerClass)
}

I absolutely agree that it's ugly and will be happy to see better solution.

Unfortunately it's not possible to use pattern matching here to make this code a little more idiomatic: How can I match classes in a Scala "match" statement?

查看更多
登录 后发表回答