我最近开始在一个小型Android项目中使用Dagger 2。我不确定我是否应该在哪里构建我的@Component
。
假设我有一个@Module
提供依赖关系,而依赖关系又依赖于Application
。显然,如果不引用@Module
,则无法实例化@Component
,因此无法构建Application
。在那种情况下,Application
本身建立并保存对@Component
的引用是否有意义,然后可以获取哪些活动和片段来进行自我注入?换句话说,代替这个:
MyComponent component = DaggerMyComponent.builder()
.myModule(new MyModule((MyApp) getApplication()))
.build();
component.inject(this);
活动只能做到这一点:
((MyApp) getApplication()).getMyComponent().inject(this);
第二种方法有什么弊端吗?如果模块提供
@Singleton
依赖关系,是否有必要采用第二种方式?编辑:我写了一个非Android测试程序。如我所料,
@Component
接口的不同实例会产生@Singleton
资源的不同实例。因此,看来我最后一个问题的答案是肯定的,除非@Component
本身具有其他某种机制。final AppComponent component1 = DaggerAppComponent.create();
final AppComponent component2 = DaggerAppComponent.create();
System.out.println("same AppComponent: " + component1.equals(component2)); // false
// the Bar producer is annotated @Singleton
System.out.println("same component, same Bar: " + component1.bar().equals(component1.bar())); // true
System.out.println("different component, same Bar: " + component1.bar().equals(component2.bar())); // false
最佳答案
您的建议是正确的。一个@Singleton
组件在其生存期内仅保证一个@Singleton
范围内的事物实例,因此您的应用程序必须保留该组件。