2015-12-08 26 views
1

我最近開始在一個小型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 

回答

1

你的建議是正確的之後,它已經創建的類。 A @Singleton組件僅保證@Singleton的一個實例 - 在其生命週期內放置了一些東西,因此您的應用程序必須保存該組件。

+0

我發現一個[教程](https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2)支持這個:「我們應該做所有這些工作在'Application'類中,因爲這些實例應該在應用程序的整個生命週期中只聲明一次。「 –

1

您的組件必須位於接口中。比方說你有一個模塊,這樣

@Module 
public class MainActivityModule { 

    @Provides 
    public Gson getGson(){ 
     return new Gson(); 
    } 
} 

現在你想一個接口,用於該模塊使您可以在活動中使用它。我注入活動到這個接口,但是當你要使用許多其他活動所以現在,我們只說你想用在MainActivity

@Component(
    modules = MainActivityModule.class) //The module you created 
public interface IAppModule { 
    void inject(MainActivity activity); 
} 

現在你可以在你的MainActivity使用,但第一,這將是非常棘手建立該項目,因爲Dagger2需要根據您所做的模塊和組件創建自己的類。需要注意的是,你還沒有做出DaggerIAppModule你已經建立了項目

IAppModule appComponent; 

@Inject 
Gson gson; 

public void setupDaggerGraph(){ //call this method in your onCreate() 
    appComponent = DaggerIAppModule.builder() 
      .mainActivityModule(new MainActivityModule()) 
      .build(); 
    appComponent.inject(this); 
} 
+0

您示例中的「@模塊」不依賴於「應用程序」。 –

+0

它在接口IAppModule的'@ Component'中使用?我不太清楚你的意思... – BigApeWhat

+0

至於你編輯的文章,你不能注入任何活動到相同的組件,你必須爲每個活動創建一個組件,並且如果你爲每個活動使用相同的模塊,你可以使用它作爲一個依賴關係,因此將使用同一個單例。 @KevinKrumwiede – BigApeWhat

相關問題