I read Dependency Injection Without the Gymnastics PDF which indicates there's no need for any fancy DI framework, but it's beyond my grasp (at least without concrete examples). I'll try watching Dependency Injection Without the Gymnastics and Dead Simple Dependency Injection when I have a chance.
Using Guice in Java, if A depends on both B and C and both B and C depend on D, one would have something like:
public class A {
@Inject
public A(B b, C c) {
this.b = b;
this.c = c;
}
}
public class B {
@Inject
public B(D d) {
this.d = d;
}
}
public class C {
@Inject
public C(D d) {
this.d = d;
}
}
public class D { /* ... */ }
and a module that says which implementation of D to use, then one would just ask for an instance of A from the injector:
A a = injector.createInstance(A.class);
Given what's presented in the URLs above, how would the Scala-equivalent of the above code look?
FWIW, I'm also investigating https://github.com/dickwall/subcut/blob/master/GettingStarted.md and am simply trying to understand the anti-DI solution.
Implicit parameters are completely sufficient for the use case you're describing.
Now you can ask for an
A
just by:It's tricky to provide that type of dependency injection. Most of the above examples require you to create the implicits near where the classes are instantiated.
Closest I could come up with is:
And then in your code you use it like this:
If you need to be able to specify different versions when you (for example) are testing, you could do something like this:
This would allow you to simply import Implicits._ in any file and would provide a similar workflow as the one in the original question.
In most cases however I would not use this tactic. I would simply make the implicit available in classes that create instances:
Here
E
is defined in another file and creates an instance ofC
. We requireD
to be passed toE
and with that document thatE
depends onD
(viaC
).I think @om-nom-nom's answer is quite close to what you want. Here is what I've got:
You may solve it with self-types.
so one could write this like that:
and then on a call side:
but code below won't compile, because dependencies on B,C,D classes not resolved: