You can look at dependency injection as a fancy name for passing parameters to a function (or constructor arguments to a constructor). However usually, DI containers do much more than that. Among other things, one very nice feature is auto-wiring: instantiating the right objects with the right arguments. Most popular frameworks (Spring, Guice, CDI/Weld) accomplish this task at runtime using reflection.
Doing the wiring at runtime with reflection has its downsides though. Firstly, there’s no compile-time checking that each dependency is satisfied. Secondly, we loose some of the flexibility we would have when doing things by hand, as we have to obey the rules by which the objects are created “automatically”. For example, if for some reason an object needs to be created manually, this requires a level of indirection (boilerplate), namely a factory. Finally, often the dependency injection is “global”, that is there is a single container with all the objects, it’s hard to create local/parametrized “universes” (Guice is an exception here). Finally-finally some frameworks do classpath scanning, which is slow, and sometimes can give unexpected results.
Way too magical for such a simple thing.
But isn’t what we really want just a way to have all the
news with correct parameters generated for us? If you’re using Scala, and want code generation, the obvious answer are macros!
To finally show some code, given:
1 2 3 4
class A class B class C(a: A, b: B) class D(b: B, c: C)
it would be nice to have:
1 2 3 4
val a = wire[A] val theB = wire[B] // "theB", not "b", just to show that we can use any name val theC = wire[C] val d = wire[D]
1 2 3 4
val a = new A() val theB = new B() val theC = new C(a, theB) val d = new D(theB, c)
Turns out it’s possible, and even not very complicated.
A proof-of-concept is available on GitHub. It’s very primitive and currently supports only one specific way of defining classes/wirings, but works :). If a dependency is missing, there’s a compile error. To check it out, simply clone the repo, run
sbt and then invoke the task:
run-main com.softwaremill.di.DiExampleRunner (implementation). During compilation, you should see some info messages regarding the generated code, e.g.:
1 2 3
[info] /Users/adamw/(...)/DiExample.scala:13: Generated code: new C(a, theB) [info] val c = wire[C] [info] ^
and then a proof that indeed the code was generated correctly: when the code is executed, the instances are printed to stdout so that you can see the arguments.
The macro here is of course the
wire method (implementation). What it does is it first checks what are the parameters of the constructor of the class, and then for each parameter, tries to find a
val defined in the enclosing class of the desired type (
findWiredOfType method; see also this StackOverflow question why the search is limited to the enclosing class). Finally, it assembles a tree corresponding to invoking the constructor with the right arguments:
1 2 3
Apply( Select(New(Ident([class's type])), nme.CONSTRUCTOR), List(Ident([arg1]), Ident([arg2]), ...))
This concept can be extended in many ways. Firstly, by adding support for sub-typing (now only exact type matches will work). Then, there’s the ability to define the wirings not only in a class, but also in methods; or extending the search to mixed-in traits, so that you could split the
wire definitions among multiple traits (“modules”?). Notice that we could also have full flexibility in how we access the wired valued; it could be a
lazy val or a
def. There’s also support for scoping, factories, singletons, configurations values, …; for example:
(Dependency Injection of the future!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
// "scopes" val a = wire[X] lazy val b = wire[Y] def c = wire[Z] val d = provided(manuallyCreatedInstance) // override a single dependency val a = wire[X].with(anotherYInstance) // factories: p1, p2, ... are used in the constructor where needed def e(p1: T, p2: U, ...) = wire[X] // by-name binding for configuration parameters; whenever a class has a // "maxConnections" constructor argument, this value is used. val maxConnections = conf(10)
A recent project by Guice’s creator, Bob Lee, goes in the same direction. Dagger (mainly targeted at Android as far as I know) uses an annotation processor to generate the wiring code; at runtime, it’s just plain constructor invocations, no reflection. Similarly here, with the difference that we use Scala’s macros.
What do you think of such an approach to DI?