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