[英]Dagger 2 Adding a subcomponent to a parent component
大家好,我對理解dagger 2以新方式添加子組件(在dagger 2.7中添加)有疑問。 請參見下面的示例:
@Component(modules = {AppModule.class, MainActivityBinder.class})
@Singleton
interface AppComponent
{
inject(MyApplication _)
}
@Subcomponent(modules = ActivityModule.class)
interface ActivitySubcomponent
{
inject(MainActivity _)
@Subcomponent.Builder
interface Builder
{
@BindInstance
Builder activity(Activity activity)
ActivitySubcomponent build();
}
}
初始步驟:我有AppComponent
與是我的根組件,其提供AppModule
用單因素(改型,okhttp等)。在ActivitySubcomponent
我提供ActivityModule
與已經指定到該活動的依賴關系。 現在必須將子組件添加到AppComponent
,因此我以新的方式創建了名為MainActivityBinder
指定模塊,該模塊具有注釋@ Module.subcomponents並指向綁定子組件,但是我首先遇到的問題是,該綁定模塊的主體應該是什么?
@Module(subcomponents = ActivitySubcomponent.class)
public class MainActivityBinder
{
//what body of this class should be ??
}
我知道,這個想法是我可以綁定子組件或其構建器。 第二個問題是何時綁定構建器,以及何時綁定子組件? 例如,我的ActivitySubcomponent
需要活動上下文,因此在這種情況下,我創建為ActivityModule
提供上下文的構建器會更好地在MainActivityBinder
提供一個構建器? 第三個問題是如何調用組件構建器以及如何為應用程序組件獲取子組件? 在標准子組件工廠中,我添加到了AppComponent
方法中,該方法返回子組件,並且我可以定義參數(例如,給出活動上下文,如下所示)
@Component(modules = {AppModule.class})
@Singleton
interface AppComponent
{
ActivitySubcomponents newActivitySubcomponents(Activity activity);
inject(MyApplication _);
}
// in MainActivity
appComponent.newActivitySubcomponents(this).build().inject(this);
那么在新的子組件添加方法中實現了此行為嗎?
您的模塊MainActivityBinder允許為空,如果沒有其他可綁定的模塊,則應為空。 當您僅使用Module.includes
,例如當您希望將模塊列表保存在一個位置而不是在多個組件之間復制時,空的(僅用於注釋的)模塊也很有用。 注釋上的subcomponents
屬性足以使Dagger了解您要執行的操作。
您可以並且僅當FooSubcomponent或Provider沒有@BindsInstance方法或可實例化模塊(Dagger無法實例化)時才可以注入。 如果所有模塊都是接口,抽象類或具有公共零參數構造函數的模塊,則可以直接注入子組件。 否則,您應該注入子組件生成器。
您可以通過創建一個在AppComponent上返回它的方法來訪問子組件構建器,就像對圖中存在的任何綁定一樣:
@Component(modules = {AppModule.class, MainActivityBinder.class}) @Singleton interface AppComponent { ActivitySubcomponent.Builder activitySubcomponentBuilder(); inject(MyApplication _) }
您也可以將其注入您選擇的對象中。
@Inject ActivitySubcomponent.Builder activitySubComponentBuilder; activitySubComponentBuilder.activity(this).build().inject(this); // You can also inject a Provider<ActivitySubcomponent.Builder> if you want, // which is a good idea if you are injecting this directly into your Application. // Your Application will outlive your Activity, and may need to inject several // instances of the Activity across application lifetime. @Inject Provider<ActivitySubcomponent.Builder> activitySubComponentBuilderProvider; activitySubComponentBuilderProvider.get().activity(this).build().inject(this);
盡管當您可以輕松地在組件上調用方法(返回構建器或返回子組件)時,注入子組件構建器似乎沒有太多優勢,但是注入構建器有兩個優點:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.