Performance Zone is brought to you in partnership with:

I am the founder and lead developer of Hibernate Envers, a Hibernate core module, which provides entity versioning/auditing capabilities. I am also one of the co-founders of SoftwareMill, a company specializing in delivering customized software solutions (http://softwaremill.com, "Extraordinary software as a standard"), based on Java and JBoss technologies. After work, apart from being involved in development of Envers, I work on several small open source projects, like ElasticMQ (simple message queue written in Scala with an SQS interface), projects around static analysis (using JSR 308 - Typestate Annotations/ Checkers Framework and FindBugs), and some CDI/Weld (not always portable) extensions, like autofactories or stackable security interceptors. I am also interested in new JVM-based languages, especially with functional elements (like Scala, JRuby) and frameworks built using them (like Lift), as well as improving the ways we use Dependency Injection. Adam is a DZone MVB and is not an employee of DZone and has posted 52 posts at DZone. You can read more from them at their website. View Full User Profile

Dependency injection with Scala macros: auto-wiring

03.18.2013
| 1725 views |
  • submit to reddit

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.

[rant]
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.
[/rant]

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:

class A
class B
class C(a: A, b: B)
class D(b: B, c: C)

it would be nice to have:

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]

transformed to:

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.:

[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:

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 val, lazy val or a def. There’s also support for scoping, factories, singletons, configurations values, …; for example:

(Dependency Injection of the future!)

// "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?



Published at DZone with permission of Adam Warski, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)