Roboguice Assisted Injection on Android

Google-guice's assisted injection extension is useful when you need to inject a contructor or method, but need to manually provide some of the parameters.

Now that Roboguice is at version 2 I thought it time to try out the assisted injection extension on Android.

The assisted inject jar comes with the guice-3.0 zip file available from http://code.google.com/p/google-guice/downloads/.

As I'm using Maven it's a case of adding the following to the dependencies in my pom:

You need the exclusions section to prevent the with aop version of guice being added (you should already have the no-aop version of guice 3.0 added). Otherwise there'll be all manner of errors.

Using it is fairly well documented on the Google-guice wiki: http://code.google.com/p/google-guice/wiki/AssistedInject

It basically comes down to 3 steps. 

  1. Create a factory interface that defines a create method, accepting the manual parameters as arguments.
  2. Use the install method in your custom module to setup the factory for injection.
  3. Annotate the constructor/method in need of assisted injection.

To use it inject an instance of the factory interface and call create on it.

The following markdown brings together an example of the four previously mentioned elements from a project (https://github.com/davespanton/Nutbar)