Does guice DI create a new WSClient instance everytime

I have a Client class that makes an API call to an external vendor. In my controller, I inject the client as follows.

@Singleton
class AdsController @Inject()(client: MyClient)(
  implicit ec: ExecutionContext
) extends InjectedController {

  def index = Action.async(json.parse[ClientRequest])  {
     client.send(request.body).map({
       case s: SuccessResponse => Ok(Json.toJson(s))
       ...
     }) 
  }
}

The client class looks as follows


class MyClient @Inject()(ws: WSClient, appConfig: Configuration)
(implicit ec: ExecutionContext) {...}

I wanted to understand two things

  1. Does the injector inject a new instance of MyClient for every request?
  2. If yes, Does the injector inject a new instance of WSClient and Configuration every time?

If both are yes then injecting configuration unnecessarily creates new instances which won’t be a good idea.

Hi @basicobject,

I think the answer to both questions is no.

Cheers,

Since you haven’t annotated MyClient with @Singleton I think you would get a new instance every time. You could easily test this with a print statement at the top level. How many times does it print something? That is

class MyClient @Inject() (ws: ...)(...) {
  println("Well, an instance of MyClient just got created!)
}

WSClient is harder because it’s buried in the Play source code. I would hope that the Play developers arranged for it to be a singleton.

Again, you could likely test this with a print statement. I would expect that println(ws) would print out its address in memory. Same address; (almost certainly) same object.