依赖注入到Scala对象(不是类) [英] Dependency injection into scala objects (not classes)

查看:92
本文介绍了依赖注入到Scala对象(不是类)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个导入"import play.api.libs.ws.WSClient",我想在我的对象中使用

I have an import "import play.api.libs.ws.WSClient" which i want to use within my object

Object X {
...

}

但这似乎在我的对象内不可用.我看到依赖项注入仅适用于类.我该如何使用它?

But this doesn't seem to be available inside my object. I see that dependency injection is only available for classes. How do i get this to work?

推荐答案

将依赖项注入对象是不可能的.

Injecting a dependency into an object is impossible.

您有两个选择:

已过时和不建议使用:通过全局应用程序访问注射器:

Ugly and deprecated: Access the injector via the global application:

val wsClient = Play.current.injector.instanceOf[WSClient]

如果代码需要存在于对象中,该怎么做:将依赖项作为参数传递.但是,这只是将问题推迟给了呼叫者.

Way to go if your code needs to live in an object: Pass the dependency in as a parameter. However this just defers the problem to the caller.

def myMethod(wsClient: WSClient) = // foo

如果您使用的是有对象并需要注入依赖的遗留应用程序,那么我认为改善"这种情况并迈向正确方向的一种方法是提供对注入类的访问,如下所示:

If youre working with a legacy application where you have objects and need an injected dependency, I think one way to "improve" the situation and make a step into the right direction is to provide access to an injected class like so:

object MyObject {
  private def instance = Play.current.injector.instanceOf[MyObject]
  def myMethod(param: String): String =
    instance.myMethod(param)
}

class MyObject @Inject() (wsClient: WSClient) {
  def myMethod(param: String): String = 
   // foo
}

这允许旧代码通过对象访问方法,而新代码可以注入依赖项.您也可以在不赞成使用的对象上注释该方法,以使用户知道.

This allows legacy code to access the methods via object, while new code can inject the dependency. You may also annotate the method on the object as deprecated so that users know.

这篇关于依赖注入到Scala对象(不是类)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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