Parameterized injection points

68 views
Skip to first unread message

limpb...@gmail.com

unread,
Nov 5, 2008, 4:11:48 AM11/5/08
to google-guice
I've added support for parameterized injection points. What's this?
Suppose you've got some parameterized class:

public class MapReducer<K,V> {
private final Mapper<K,V> mapper;
private final Reducer<V> reducer;

@Inject
MapReducer(Mapper<K,V> mapper, Reducer<V> reducer) {
this.mapper = mapper;
this.reducer = reducer;
}
}

...and some specific bindings:
public class WordCounterModule extends AbstractModule {
public void configure() {}

@Provides
Mapper<String, Integer> provideStringIntegerMapper() {
return new WordCounter();
}

@Provides
Reducer<Integer> provideIntegerReducer() {
return new Adder();
}
}

This change allows you to inject a MapReducer<String, Integer>. Guice
will resolve the type parameters K and V to String and Integer, and
use the appropriate dependencies.

For things to work, all types must be fully specified -- Guice cannot
inject a K, unless it knows what type K maps to. We can inject a
MapReducer<String, Integer>, but never a MapReducer<K, V> or a raw
MapReducer.

I don't predict this feature will be very popular, but it means things
Just Work regardless of how you structure your application classes.
For example, you can now parameterize an arbitrary dependency and
Guice won't get in your way.

This code's is in SVN, and examples are in the test case:
http://code.google.com/p/google-guice/source/browse/trunk/test/com/google/inject/GenericInjectionTest.java

Still outstanding is some optimization. Currently we do some type
resolutions eagerly that will slow things down in the non-
parameterized case.

Cheers,
Jesse

Logan Johnson

unread,
Nov 5, 2008, 7:17:27 AM11/5/08
to google...@googlegroups.com
I think this will be more popular than you think it will.  It'll be huge for guice-enabled frameworks and libraries that want to expose a simple binding DSL.

The use case in my project is transformation pipelines.  We basically have a library for them that includes all sorts of messaging infrastructure, and I'd already written a tight little binding builder for it before I realized this issue would scuttle it.
Reply all
Reply to author
Forward
0 new messages