Guice in Android without Use Roboguice, good choice?

416 Views Asked by At

I have been using Roboguice for a while but as I see the source code in github, it has a lot of unnecessary stuff that I am not typically use it or need it, so I decided to start working only with Guice. The only drawback with this is that I need to inject the Android Context and configure by myself, so I end up doing this:

public class AndroidDemoApplication extends Application {

    private static AndroidDemoApplication instance;
    private static final Injector INJECTOR = Guice.createInjector(new AndroidDemoModule());

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static Context getAppContext() {
        return instance;
    }

    public static void injectMembers(final Object object) {
        INJECTOR.injectMembers(object);
   }

}

And then in my class that extends AbstractModule:

    public class AndroidDemoModule extends AbstractModule {

    @Override
    protected void configure() {

        bind(Context.class).toProvider(new Provider<Context>() {
            @Override
            public Context get() {
                return AndroidDemoApplication.getAppContext();
            }
        });
//        .in(Singleton.class);
    }
}

Is it a good approach? For now I just only need the Context to use in let say a Session manager which needs the context to create a sharedPreference instance and play with it.

Finally: is it a good approach to replace Roboguice with Guice when I only want to inject My Objects and not anything related to Android, only the Context? And use something more lightweight and less dependent than Roboguice. After all Dagger does something similar, right?

1

There are 1 best solutions below

6
On

it has a lot of unnecessary stuff that I am not typically use it or need it

This does not make sense : use ProGuard in order to get rid of the classes you are not using (and minify for the resources with Gradle 0.14).

There is a reason behind the development of RoboGuice : Guice has been written with the desktop in mind. It uses reflection quite heavily. It is not an issue on desktop, but on mobile reflection perform pretty badly.

You should either stick with RoboGuice or maybe consider Dagger 2. It is right now pretty close to a release and has been written by the Guice guys as a modern and fast (no reflection at all, the magic happens at compile time) dependency injection lib for Android.