Search code examples
scalaplayframeworkguice

How to inject singleton class in another class with constructor parameters in scala and create it's objects just the constructor?


I have a singleton class:

@Singleton
class Inject_Class_A @Inject()(
                            wsClient: WSClient,
                          )(implicit executionContext: ExecutionContext) {
// ... does something

}

I have another main class in which I want to inject the previous class, it also have other construct parameters. IDE says it is syntactically correct:

class Main_Class @Inject()(
                           inject_class_A: Inject_Class_A,
                           implicit val executionContext: ExecutionContext
                           )(key: String, value: String) {

// ... does something different using inject_class_A
}

Now I want to create objects as:

val main_class = new Main_Class(key: "KEY", value:"VALUE")

Ofcourse it gives error:

Unspecified value parameters: inject_class_A: Inject_Class_A, executionContext: ExecutionContext

I tried this way also:

class Main_Class(key: String, value: String) {

  @Inject val inject_class_A: Inject_Class_A = new Inject_Class_A()

// ... does something different using inject_class_A
}

But this doesn't work as I don't have wsClient: WSClient and executionContext: ExecutionContext and these I get only from injection only.


Solution

  • With standard Guice, you can either have a class injected or instantiate it yourself. Not both at the same time. You could inject into an existing instance, but that's ugly. If you need an injected instance with runtime-determined parameters, you should look into Assited injection.