从Scala伴随对象调用Controller的方法 [英] calling methods of Controller from scala companion objects

查看:95
本文介绍了从Scala伴随对象调用Controller的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目中有一个控制器,该控制器具有 socket方法,我想在随播对象中调用该方法.但由于某种原因,我还无法将其传递给随播对象,因此我无法做到这一点对象,我做不到. 这是我的代码示例:

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 ???*/

}

推荐答案

虽然在技术上可行,但您不应该这样做,因为静态调用方法使您的代码紧密耦合,并抵消了依赖注入的其他好处,例如测试中的模拟

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.

应如何做: 无论您打算在伴随对象中执行什么操作,请在其他class中执行该操作,然后注入该类.

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.

如何继续使用随播对象 请注意,此功能在播放2.5中已弃用,在播放2.6中将被删除,但是如果您确实想在同伴对象中获取该类的实例,则可以执行以下操作:

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.

这篇关于从Scala伴随对象调用Controller的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆