【发布时间】:2017-06-15 18:10:42
【问题描述】:
我正在将 Dagger 2 设置到我的 android 项目中。这是我第一次使用这个框架,到目前为止一切顺利。但是我看到了在项目中设置这个框架的不同方法,我想知道哪个更好,因为我比较了两者,对我来说结果是一样的。
我遵循了这个指南:https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2
在互联网上搜索他们都使用这种方法。 它使用@Module 和@Component 来定义依赖关系。
你的应用程序最终是这样的:
public class MyApp extends Application {
private NetComponent mNetComponent;
@Override
public void onCreate() {
super.onCreate();
// Dagger%COMPONENT_NAME%
mNetComponent = DaggerNetComponent.builder()
// list of modules that are part of this component need to be created here too
.appModule(new AppModule(this)) // This also corresponds to the name of your module: %component_name%Module
.netModule(new NetModule("https://api.github.com"))
.build();
// If a Dagger 2 component does not have any constructor arguments for any of its modules,
// then we can use .create() as a shortcut instead:
// mNetComponent = com.codepath.dagger.components.DaggerNetComponent.create();
}
public NetComponent getNetComponent() {
return mNetComponent;
}
}
但是我找到了另一种方法(我没有测试过):https://google.github.io/dagger/android.html 它看起来完全不同,使用不同的类和注释。 它使用这样的东西:
@Subcomponent(modules = ...)
public interface YourActivitySubcomponent extends AndroidInjector<YourActivity> {
@Subcomponent.Builder
public abstract class Builder extends AndroidInjector.Builder<YourActivity> {}
}
@Module(subcomponents = YourActivitySubcomponent.class)
abstract class YourActivityModule {
@Binds
@IntoMap
@ActivityKey(YourActivity.class)
abstract AndroidInjector.Factory<? extends Activity>
bindYourActivityInjectorFactory(YourActivitySubcomponent.Builder builder);
}
@Component(modules = {..., YourActivityModule.class})
interface YourApplicationComponent {}
public class YourApplication extends Application implements HasDispatchingActivityInjector {
@Inject DispatchingAndroidInjector<Activity> dispatchingActivityInjector;
@Override
public void onCreate() {
super.onCreate();
DaggerYourApplicationComponent.create()
.inject(this);
}
@Override
public DispatchingAndroidInjector<Activity> activityInjector() {
return dispatchingActivityInjector;
}
}
所以,我的问题是:
哪个更好?
选择一种方法而不是另一种方法的原因是什么?
【问题讨论】:
-
你能详细说明有什么不同吗?
-
另外,看看这个github.com/googlesamples/android-architecture/tree/… 通常我会遵循谷歌推荐的任何内容。他们维护 Dagger 2 :D
-
我附上了代码中的主要区别,以便更好地了解我在说什么!!
-
@Shmuel 您提供的示例回购代码与我编写的相同。但是这个链接 (google.github.io/dagger/android.html) 显示的是不同的东西。如您所见,该网址也来自谷歌=P。也许我错过了什么。
-
你会发现 Dagger 的十几种不同的实现方式,复杂程度不一。最后一个示例看起来像是生成注入过程并使用子组件 - 老实说,我尝试使用 KISS 原则。考虑到这两个中的哪一个将适合您的目的,同时实现相同的目标。对我来说,DI 应该用这个库解决的令人头疼的问题正在被它越来越复杂的实现所抵消。