About Adam Warski

Adam is one of the co-founders of SoftwareMill, a company specialising in delivering customised software solutions. He is also involved in open-source projects, as a founder, lead developer or contributor to: Hibernate Envers, a Hibernate core module, which provides entity versioning/auditing capabilities; ElasticMQ, an SQS-compatible messaging server written in Scala; Veripacks, a tool to specify and verify inter-package dependencies, and others.

Dependency injection with Scala macros: auto-wiring

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:

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:

   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?

Reference: Dependency injection with Scala macros: auto-wiring from our JCG partner Adam Warski at the Blog of Adam Warski blog.

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Leave a Reply

one × = 4

Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books