我最近開始在一個小型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
資源的不同實例。所以看起來,我最後一個問題的答案是肯定的,除非有一些其他機制可以作爲單身人士。
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
我發現一個[教程](https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2)支持這個:「我們應該做所有這些工作在'Application'類中,因爲這些實例應該在應用程序的整個生命週期中只聲明一次。「 –