ScalaWS in play framework 2.5 and dependency injec

2019-08-12 18:11发布

问题:

I'm using Scala Play framework 2.5 and I would like to use dependency injection to inject an instance of WSClient into my custom class but I keep getting the following error.

not enough arguments for constructor TestClass: (ws: play.api.libs.ws.WSClient)service.TestClass. Unspecified value parameter ws.

I get the error when running the following code

class TestClass @Inject() (ws: WSClient) {
  def doSomething() : Future[WSResponse] = {
    ws.url("http://www.google.com").get()
  }
}

val test = new TestClass()
val f = test.doSomething()
val result = Await.result(f, Duration.Inf)

println("doSomething: " + result)

Can someone help me resolve this problem of trying to inject a wsclient dependency into a custom class?

Thanking you in advance

Francis

回答1:

This line:

val test = new TestClass()

It is not using the dependency injection support provided by Play. You are manually creating the instance of TestClass. I truly recommend that you read the following doc page:

PlayFramework: Scala Dependency Injection

Basically, when using runtime Dependency Injection, you don't create the instances manually. You let the DI framework do the job for you. But, if you are instead interested in compile time dependency injection, see the following page:

PlayFramework: Compile Time Dependency Injection