Multiple injectors?

6 views
Skip to first unread message

Dave Halliday

unread,
Jan 2, 2008, 4:58:47 PM1/2/08
to google-guice
Happy New Year!

I'm considering using Guice for an a new application. For each
request (via Java RMI) I would like to vary the Module list depending
on the request type. There are about a dozen different request
types. Each request requires a common set of classes along with
several classes that depend on the request type.

Does it make sense to create a separate injector for each request type
and then choose the right one when the request arrives?

Or is there some way to use scopes to solve this problem?

Thanks,

Dave

Robbie Vanbrabant

unread,
Jan 2, 2008, 5:43:36 PM1/2/08
to google...@googlegroups.com
Consider injecting Provider<T> instances. Then you can choose the returned object graph by varying the "root" object that gets returned. Unused object graphs don't get created.

pseudo code:
// instance variable, you will probably want to maintain a collection of providers
@Inject @ReallyFast Provider<? extends SomeBaseType> reallyFastProvider;

public <T extends SomeBaseType> T getSomething(Request request) {
    if (Type.REALLY_FAST.equals(request.getType())
        return reallyFastProvider.get();
    else
       // ...
}

Guice makes Provider<T> instances available for all its bindings, even if you didn't use bind(...).toProvider(...).
You can scope the providers (the original bindings) if you want to. It all depends on what you want to achieve.

If the object graphs are only slightly different (you can't vary "root" objects without some serious duplication), then you have what they call the "robot legs" problem.
Then you'll need the different injectors like you said.

Hope I'm making sense,
Robbie

Robbie Vanbrabant

unread,
Jan 2, 2008, 5:47:03 PM1/2/08
to google...@googlegroups.com
That should be
@Inject @ReallyFast Provider<SomeBaseType> reallyFastProvider;
Reply all
Reply to author
Forward
0 new messages