如何使用 MacWire(播放框架)向服务注入依赖项 [英] how to inject dependencies to a service with MacWire (play framework)
问题描述
我有一个服务类,服务有一个方法 getSomethingFromApi
,现在,我想要播放配置实例,以便我可以从 application.conf 中提取内容,以及播放 WSClient,所以我可以执行http调用.
I have a service class, and the service have one method getSomethingFromApi
, now , I want to have play Configuration instance so I can pull stuff from the application.conf, and a play WSClient so I can perform http calls.
这就是我希望我的服务的外观:
this is how I want my service to look:
class MyApiService {
def getSomethingFromApi(whichApi: String): Future[ApiRes] = {
wsClient.url(configuration.getString(whichApi)).withHttpHeaders(("Content-Type", "application/json")).get.map { res =>
response.status match {
case Status.OK => // do something
case _ => throw new Exception
}
}
}
}
这是连接我的服务的 ServicesModule:
and this is the ServicesModule that is wiring my services:
import com.softwaremill.macwire._
trait ServicesModule {
lazy val myService: MyApiService = wire[MyApiService]
}
我现在的问题是使用连线播放配置和 WSClient 实例的正确方法是什么..?因为目前我在我的服务中需要这些实例,但我没有它们,我应该如何以正确的方式做到这一点?谢谢
my question now is what is the right way of using wiring play Configuration and WSClient instances..? cause currently i need those instances in my service but i dont have them, how should i do this the right way? thanks
推荐答案
对于配置我建议使用类似 PureConfig 并按如下方式加载配置
For the configuration I suggest using something like PureConfig and load the configuration as follows
import pureconfig._
import pureconfig.error.ConfigReaderFailures
case class YourConfClass(name: String, quantity: Int)
val config: Either[pureconfig.error.ConfigReaderFailures,YourConfClass] = loadConfig[YourConfClass]
然后可以使用 macwire 将其传递给应用的任何组件.
This then can be passed on to any component of your app using macwire.
从 Play 2.6.X 开始,应该使用 ws
依赖项提供的 AhcWSComponents
,如下所示:
As of Play 2.6.X one should use AhcWSComponents
that are provided by the ws
dependency as follows:
在您的 build.sbt 文件中,将 ws 依赖项添加到您的项目中
In your build.sbt file add the ws dependency to your project
libraryDependencies += ws
在你的模块 trait 中混合 AhcWSComponents
trait 并连接 WSClient
In your module trait mix-in the AhcWSComponents
trait and wire the WSClient
trait ServicesModule with AhcWSComponents {
lazy val wsClient = wire[WSClient]
lazy val apiService = wire[MyApiService]
}
在您的 MyApiServic
e 中添加 WSClient
作为参数.给构造函数
In your MyApiServic
e add the WSClient
as a param. to the constructor
class MyApiService(wsClient: WSClient) { ... }
现在你完成了.此一般规则适用于所有提供的依赖项.
And now you're done. This general rule applies to all provided dependencies.
这篇关于如何使用 MacWire(播放框架)向服务注入依赖项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!