2017-02-16 36 views
0

您好,我是Dagger2的新手。 目標。拿我的網絡DI和MVP DI。 MVP和主持人一樣,可以擴展基本活動。我想把所有這些結合到一個超級模塊中,並將其放入我的基本活動中。隨着時間的推移添加更多的演示者。Dagger 2如何爲所有MVP組件創建基本活動組件模塊和單獨模塊

我不想在我的baseActivity中使用30+注入語句。 我正在關注this example,但與我正在嘗試做的相比,它太簡單了。

我認爲問題在於在基本活動中注入API。出於某種原因,Dagger在我的MVP類中尋找Api。那麼這將是一個依賴關係圖的問題?

花了更多的時間在這..這個問題源於Mvp的baseActivity接口或任何擴展baseActivity的子活動。這意味着當它注入時,它會看到@inject Api調用,並且找不到它。如果我將Api添加到此模塊中,它會起作用,但是它會顛倒我想要的。我想要應用程序級別項目的組件/模塊。然後我想要一個組件/模塊,它在一個模塊中包含我所有不同的MVP組件。就像Dagger開始在樹的葉中尋找依賴關係並且在根本沒有看到什麼時開始感到不安。我需要它走另一條路。滿意我在Root活動中注入了依賴關係。

基本活動......

@inject 
public ApiClient mClient; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    mManager = new SharedPreferencesManager(this); 
    DaggerInjector.get().inject(this); 
} 

DaggerInjector

public class DaggerInjector { 
private static AppComponent appComponent = DaggerAppComponent.builder().appModule(new AppModule()).build(); 

public static AppComponent get() { 
    return appComponent; 
} 
} 



@Component(modules = {AppModule.class, ApiModule.class, MvpModule.class}) 
@Singleton 
public interface AppComponent { 

    void inject(BaseActivity activity); 


} 

阿比

@Singleton 
@Component(modules = {ApiModule.class}) 
public interface ApiComponent { 
    void inject(BaseActivity activity); 
} 



@Module 
public class ApiModule { 

    @Provides 
    @Singleton 
    public ApiClient getApiClient(){ 
     return new ApiClient(); 
    } 
} 

MVP

@Singleton 
@Component(modules = {MvpModule.class}) 
public interface MvpComponent { 
    void inject(BaseActivity activity); 
} 

@Module 
public class MvpModule { 

    @Provides 
    @Singleton 
    public MvpPresenter getMvpPresenter(){ return new MvpPresenter();} 
} 



Error:(16, 10) error: ApiClient cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. This type supports members injection but cannot be implicitly provided. 
ApiClient is injected at 
...BaseActivity.ApiClient 
...BaseActivity is injected at 
MvpComponent.inject(activity) 
+0

我認爲你的問題是,匕首試圖提供一個''從B_Component' A_Client'對象不存在有。爲什麼不能有一個組件並在那裏安裝兩個模塊? – benji

+0

現在B是空的,什麼都不做。這將是我的MVP主持人。你是說有一個組件可以執行MVP代碼,我的網絡代碼和其他10個未連接的項目嗎? – StarWind0

+0

我重命名了組件。 A現在是Api和B現在是MVP。 – StarWind0

回答