[英]For Dagger 2, what is the best way to access an instance inside 1 module from other modules?
只是在Android應用程序中試用Dagger 2,我覺得對於我要實現的目標可能會有更簡單的解決方案。
我有2個模塊:
顧名思義, ApplicationModule
的生命周期與整個應用程序相關。
每當用戶登錄時,都會創建UserModule
。
現在說我有一個在ApplicationModule
創建的Singleton Prefs
實例,但是我需要在UserModule
中的類中訪問它,最好的方法是什么? 當前,我正在ApplicationModule中創建它,然后在創建它時將其傳遞到UserModule的構造函數中。 有沒有辦法避免這樣做,而讓Dagger為我管理呢?
@Module
public class ApplicationModule {
@Provides
@Singleton
public Prefs prefs() {
return new Prefs();
}
}
@Singleton
@Component(modules={ApplicationModule.class})
public interface ApplicationComponent {
Prefs providePrefs();
}
@Module
public class UserModule {
private Prefs prefs;
public UserModule(Prefs prefs) {
// Anyway to avoid having to do this?
this.prefs = prefs;
}
@Provides
@UserScope
public UserService userService() {
// Possible to get the prefs from the ApplicationComponent?
return new UserService(this.prefs);
}
}
@Component(dependencies = {ApplicationComponent.class}, modules = {UserModule.class})
@UserScope
public interface UserComponent extends ApplicationComponent {
UserService provideUserService();
}
匕首的全部目的是讓它為您解決依賴性。 您不需要將不需要直接傳遞的任何內容傳遞到模塊中,例如用戶模塊的實際用戶。
依賴關系將通過匕首解決。 在您的情況下,這意味着要像這樣修改代碼:
@Module
public class UserModule {
public UserModule() {
// way of avoiding this code ;)
}
@Provides
@UserScope
public UserService userService(Prefs prefs) {
return new UserService(prefs);
}
}
這種匕首將提供對方法的依賴。 您不必自己做。
這項工作的前提條件是可以實際提供依賴項。 在您的情況下, Prefs
由應用程序組件提供。 只要實例化@Subcomponent
或實例化具有@Subcomponent
依賴關系的@Component
,它都將起作用—應用程序組件中的Prefs providePrefs()
方法。
如果提供依賴關系的模塊在同一組件中,則這也將起作用。
如果您的UserService
依賴其他任何內容,您甚至可以考慮刪除整個模塊,因為看起來它可以由構造函數注入提供。
@UserScope
public class UserService {
Prefs prefs;
@Inject
public UserService(Prefs prefs) {
this.prefs = prefs;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.