当前位置: 代码迷 >> Android >> Dagger 2如何为基本活动组件创建模块以及为所有MVP组件创建单独的模块
  详细解决方案

Dagger 2如何为基本活动组件创建模块以及为所有MVP组件创建单独的模块

热度:50   发布时间:2023-08-04 11:15:19.0

您好,我是Dagger2的新手。 目标。 拿我的网络DI和MVP DI。 演示者中的MVP,用于扩展基本活动的活动。 我想将所有这些组合到一个超级模块中,并将其放入我的基本活动中。 随着时间的推移,添加更多的演示者。

我不想在baseActivity中使用30多个inject语句。 我正在跟踪但与我尝试执行的操作相比,它太简单了。

我认为问题在于在基本活动中注入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);


}

API

@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)

我发现了我的问题。 我需要使用一个子组件。

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

@Module
public class MvpModule {

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

看到