Tuesday, January 26, 2010

toInstance in Google GIN

Couldn't find anything like toInstance in GIN, so I've developed one myself. Here is the patch against svn revision 135: instance-patch.diff
Usage: declare void methods named like "setXXX" in your ginjector:
interface MyGinjector extends Ginjector {
 void setSomething(Something real);
 void setAnotherThing(@Named("ID") int id);
 void setAlltogether(Something real, @Named("ID") int id);
 void setOptional(@Optional Object object);
}

Once all non-optional dependencies are set, you can call any other ginjector methods. It's that simple. I've included some tests which you can use as an example.

The curious thing is that you can chain your ginjectors together:
interface ParentGinjector extends Ginjector {
 void injectMembers(ChildGinjector inj);
}

interface ChildGinjector extends Ginjector {
 @Inject void setSomething(Something real);
 @Inject void setAnotherThing(@Named("ID") int id);
}

Note the @Inject annotation in the child injector. Now you can simply:
  ChildGinjector child = GWT.create(ChildGinjector.class);
 parent.injectMembers(child);

This is the pre-built version on google gin 1.0 with that patch:
GWT version < 2.3: gin.jar

4 comments:

danidacila said...

I think @Inject should be specified at method level:

@Inject
void setSomething(Something real);
@Inject
void setAnotherThing(@Named("ID") int id);

Am I right?

Dmitry Negoda said...

Sure! I'm so absent-minded! Thank you for the tip

danidacila said...

Thanks for your ideea.
The code works perfectly.

Have you considered somehow commiting your changes to gin trunk?

So later builds of gin will include your patch?

Dmitry Negoda said...

Yes, I have proposed the patch but they haven't released it yet.