Reputation: 11888
Imagine a class B as follow :
class B @Inject() (wsClient: WSClient) {
...
}
Then in another class A, I need to instantiate B :
class A {
val b = new B()
}
It's gonna complain saying that I haven't specified wsClient in my constructor. One way to fix this is to modify A :
class A @Inject() (wsClient: WSClient) {
val b = new B(wsClient)
}
I could also add an Implicit in my class B. But in both case, it just seems very wrong to me to send the dependency like this ...
How could I do it in a more elegant way ?
Upvotes: 0
Views: 79
Reputation: 2095
The whole point of doing DI is to have inversion of control. Your bindings decide how the application is built as opposed to the classes in the application being responsible for their own control flow.
The line val b = new B(wsClient)
is a violation of this principle as the class is responsible for knowing how it should constitute itself as opposed to the DI framework being responsible for that.
class B @Inject() (ws: WSClient){}
class A @Inject() (b: B) // extends B
{}
As @zoltan alluded to, injecting B into A would be the right way to go about solving the problem.
Upvotes: 2
Reputation: 22206
Why not have B
injected into A
?
class A @Inject() (b: B)
if your class B
needs to be a singleton, just annotate it with javax.inject.Singleton
.
Upvotes: 1