我對Dagger2比較新,但是我喜歡在項目中使用它的優點。我目前正在嘗試瞭解自定義範圍。DI與Dagger 2,替換構建組件上的子組件
我有這個基本的應用程序設置:ApplicationComponent
,ActivityComponent
,UserComponent
。這就是我打算在他們在我的應用程序
[-----------User scope-------------]
[ Activity scope ][ Activity scope ][ Activity scope ][ Activity scope ]
[-----------------------Aplication Scope (Singleton)-------------------]
在中間的兩個活動的用戶登錄到工作
我的依賴關係圖如下所示:AplicationComponent
< - ActivityComponent
< - UserComponent
UserComponent
依賴於ActivityComponent
工作,而ActivityComponent
依賴於AplicationComponent
。
UserComponent
只是一個「專業」ActivityComponent
,也提供當前登錄的用戶。 不需要用戶的活動只需使用ActivityComponent
注入,那些需要注入用戶的用戶需要使用UserComponent
。希望它是有道理的。
當用戶第一日誌中,我創建了當前活動的UserComponent
:
ActivtyComponent activityComponent = DaggerActivityComponent.builder()
.activityModule(new ActivityModule(this)) //** here, 'this' is the current Activity
.applicationComponent(MyApplication.getApp(getActivity()).getAppComponent())
.build();
UserComponent userComponent = DaggerUserComponent.builder()
.activityComponent(activityComponent)
.build();
userComponent.inject(this);
//Store user component to be retrieved by other activities
MyApplication.getApp(getActivity()).storeUserComponent(userComponent);
這工作得很好。現在,假設我開始一個新的活動,並嘗試注入它的依賴關係。這一次更容易,我已經有了一個UserComponent存儲了這個原因!我可以使用那個,對吧?:
MyApplication.getApp(getActivity()).getUserComponent().inject(this);
錯!!它會崩潰!因爲該組件仍然具有存儲在其活動模塊中的先前活動(**見上面的代碼)
而且我不想創建另一個UserComponent,這會導致範圍無用...將調用所有提供的方法再次,我是對的嗎?我需要那個特定的組件,而不是一個新的組件。但我必須以某種方式交換其ActivityComponent爲一個新的,新的將有這項活動傳入其activityModule ...這是我的問題:
這可能嗎?我以正確的方式看待這個嗎? 我可以更改已構建組件中的子組件嗎?
在此先感謝
我注意到大多數教程都使用你提到的依賴順序。我已經嘗試過它,它的工作原理!我只是不喜歡它,因爲每次創建ActivityComponent時它都會強制提供一個UserComponent。這是針對所有活動的,即使是沒有用戶注入的「註銷」活動,這也沒什麼意義。我注意到,你提到的依賴順序遵循這個規則,其中較短生命期的範圍依賴於較長生命週期的範圍,所以必須有一些它。感謝您的直接解釋,現在很清楚爲什麼hotswapping組件不方便 – feresr
@feresr您可以爲不同的活動有不同的組件。有些則取決於用戶,應用程序組件上的其他人 –
是的,我看到有人這樣做。它是一種有效的方法。就我個人而言,我喜歡讓我的組件更具通用性/抽象性,我不想結束大量組件。如果應用程序在將來需要更多活動。我會用第一種方法:) – feresr