scaladependency-injectionplayframeworkguicews-client

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.


Solution

  • Guice by default always create a new instance. Unless you configured it to reuse the instance by e.g. annotating object as @singleton or configuring Provider that uses some cache or using bind to explicitly point to the instance that should be used when some class is required..

    This is a desired behavior, as there are many issues and errors related to using singletons (e.g. it's easier to produce a memory leak with them), so this has to be a conscious, explicit decision of a programmer, who should make sure that it won't bite them.