2017-07-04 44 views
2

我有一個依賴於Play的Configuration和WSClient實例的api服務類。無法與Macwire連線播放依賴關係

,我不想使用@Inject()anotation因爲我想使用編譯時注射Macwire因此,我所做的是:

// this is a trait that here im wiring all the dependencies that my api service needs 
trait ApiDependencies { 

    lazy val conf: Configuration = wire[Configuration] 
    lazy val wsc: WSClient = wire[WSClient] 

} 


// this is the api service 

class ApiService extends ApiDependencies { 

    def getInfo (id: String): Future[Option[Info]] = { 
    wsc.url("...").withHttpHeaders(("Content-Type", "application/json")).get.map { response => 
     response.status match { 
     case Status.OK => ... 
     case Status.NO_CONTENT => ... 
     case _ => throw new Exception() 
     } 
    } 
    } 
} 

但我得到一個編譯器錯誤:

Error: Cannot find a value of type: [com.typesafe.config.Config]
lazy val conf: Configuration = wire[Configuration]

Error: Cannot find a public constructor nor a companion object for [play.api.libs.ws.WSClient] lazy val wsc: WSClient = wire[WSClient]

有人知道我該如何解決這個問題......?爲什麼發生這種情況:/

謝謝!

+1

可能的重複[如何注入與MacWire服務依賴關係(玩框架)](https://stackoverflow.com/questions/44875361/how-to-inject-dependencies-to-a-service-with- macwire-play-framework) –

回答

0

Configuration是一個playframework配置,其中internally uses Typesafe的Config library。引用Playframework docs

The configuration file used by Play is based on the Typesafe config library

你得到的異常告訴你,正是這個 - macwire不能因爲有在範圍上沒有Config實例來創建的Configuration一個實例。

要解決這個問題,你顯然需要提供這樣的instace。這樣做最簡單的方法很可能是這樣的:

import com.typesafe.config.{Config, ConfigFactory} 
trait ApiDependencies { 
    lazy val configuration: Config = ConfigFactory.load() 
    lazy val conf: Configuration = wire[Configuration] 
} 

注意ConfigFactory.Load()基本上採用默認的配置文件(application.conf),它確實考慮配置覆蓋在Play's Configuration docs描述的技術,因爲它實際上是由提供類型安全配置庫(從類型安全配置GitHub的自述):

users can override the config with Java system properties, java -Dmyapp.foo.bar=10


關於WSClient:噸他是因爲WSClient不是班級,而是a trait。您需要連線實際執行,即NingWSClient,像這樣:

trait ApiDependencies { 
    lazy val conf: Configuration = wire[Configuration] 
    lazy val wsc: WSClient = wire[NingWSClient] 
} 

WSClient scaladoc用於實現類的清單(「所有已知實現類」下) - 寫的時候,都只有NingWSClientAhcWSClient。哪一個更好是一個不同的(可能是基於觀點的問題)。

+0

你是否有WSClient錯誤的答案......也得到這個:/ @ J0HN – JohnBigs

+0

是的,你知道如何解決WSClient錯誤..? –

+0

@JohnBigs我已經更新了答案 - 請看一看,讓我知道它是否有幫助 – J0HN