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.

  • What are you trying to achieve by manually instantiating the Main_Class? Is this in a test context?

    – 

  • Nope. You can imagine it as there are several accounts, and each has its own keys, say apiKey. This key is used in the Inject_Class_A functions and in the Main_Class functions as well. Now I want to create a single Main_Class object for each account. The function of Inject_Class_A is common for each account, and it needs to have wsClient and executionContext which is only received via @Injection in Play.

    – 




  • I don’t know if this is possible or not but since the Main_Class definition is syntactically correct, I am hoping it is.

    – 

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.

Leave a Comment