calling methods of Controller from scala companion objects

淺唱寂寞╮ 提交于 2019-12-25 07:15:12

问题


I have a controller in my project which has a socket method I want to call that method in companion object.But somehow i am not able to do that as i need to pass parameters also to companion object , which i can't . Here's my code sample:

class WebSocketController @Inject() (cache:CacheApi)(implicit actorSystem:ActorSystem, materializer:Materializer) extends Controller {

def socket  = WebSocket.accept[JsValue , JsValue] { request => 
ActorFlow.actorRef(out => SocketHandlerClass.props(out,postActor))

}


}


/*My Companion Object */

object WebSocketController {

/* how to call socket method here ???*/

}

回答1:


While technically possible, you shouldn't be doing that, because statically calling methods makes your code tightly coupled and defeats other benefits of dependency injection such as mocking in tests.

How you should do it: Whatever you plan to do in the companion object, do that in some other class and then inject that class.

How you could still do it with the companion object Note that this is deprecated with play 2.5 and will be removed with play 2.6, but if you really want to get an instance of that class inside the companion object, you can do this:

Play.current.injector.instanceOf[WebSocketController]

However besides this essentially defeating dependency injection, calling a controller's method from outside looks like a rather unfortunate design choice. Controllers shouldn't contain any logic - and as said above - you should extract you logic to another class an inject that into the controller.



来源:https://stackoverflow.com/questions/38141902/calling-methods-of-controller-from-scala-companion-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!