如何使用MacWire(播放框架)向服务注入依赖项 [英] how to inject dependencies to a service with MacWire (play framework)
问题描述
我有一个服务类,并且该服务具有一个方法getSomethingFromApi
,现在,我想拥有一个播放Configuration实例,以便可以从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.
从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
在模块特征中混入AhcWSComponents
特征并连接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屋!