0

我一直在使用 Roboguice,但是当我在 github 上看到源代码时,它有很多我通常不使用或不需要它的不必要的东西,所以我决定开始只使用 Guice。唯一的缺点是我需要自己注入 Android Context 和配置,所以我最终这样做了:

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);
   }

}

然后在我扩展 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);
    }
}

这是一个好方法吗?现在我只需要使用上下文,比如说一个会话管理器,它需要上下文来创建一个 sharedPreference 实例并使用它。

最后:当我只想注入我的对象而不是任何与 Android 相关的东西,只有上下文时,用 Guice 替换 Roboguice 是不是一个好方法?并使用比 Roboguice 更轻量级和更少依赖的东西。毕竟 Dagger 做了类似的事情,对吧?

4

1 回答 1

0

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.

于 2014-11-27T22:28:56.787 回答