如何在Activity及其父项中添加DI(匕首2)

时间:2018-09-04 08:11:33

标签: android dependency-injection dagger-2 dagger

我在我的android项目中使用了Dagger 2,并且想在一个Activity和另一个Activity中使用@Inject来扩展第一个-> MainActivity扩展NetworkBaseActivity。在onCreate()方法内的两个活动中,我都有这个:

AndroidInjection.inject(this);

另外,我有下一个结构:

@Singleton
@Component(modules = {
    AndroidInjectionModule.class,
    AppModule.class,
    ActivityBuilderModule.class,
    WebServiceModule.class})
public interface AppComponent {

    @Component.Builder
    interface Builder {

        @BindsInstance
        Builder application(Application application);

        AppComponent build();
    }

    void inject(App app);

}

@Module
public abstract class ActivityBuilderModule {

    @ContributesAndroidInjector(modules = {NetworkActivityModule.class})
    public abstract NetworkBaseActivity bindNetworkBaseActivity();

    @ContributesAndroidInjector(modules = {MainActivityModule.class})
    public abstract MainActivity bindMainActivity();    
}

@Module
public class NetworkActivityModule {

    @Provides
    public NetworkViewModelFactory 
    provideNetworkViewModelFactory(AuthRepository authRepository) {
    return new NetworkViewModelFactory(authRepository);
    }

    @Provides
    public AuthRepository provideAuthRepository(WebServiceApi webServiceApi, 
    SharedPreferencesManager sharedPreferencesManager) {
        return new AuthRepository(webServiceApi, sharedPreferencesManager);
    }
}

@Module
public class MainActivityModule {

}

在我的Application类的onCreate()回调中,我有以下内容:

DaggerAppComponent
            .builder()
            .application(this)
            .build()
            .inject(this);

但是会收到此错误:

error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] 
com.example.android.view.base.NetworkViewModelFactory cannot be provided 
without an @Inject constructor or an @Provides-annotated method.
A binding with matching key exists in component:  
com.example.android.data.di.ActivityBuilderModule_BindNetworkBaseActivity
.NetworkBaseActivitySubcomponent
com.example.android.view.base.NetworkViewModelFactory is injected at
com.example.android.view.base.NetworkBaseActivity.mViewModelFactory
com.example.android.view.main.MainActivity is injected at
dagger.android.AndroidInjector.inject(T)
component path: com.example.android.data.di.AppComponent ?  
com.example.android.data.di.ActivityBuilderModule_BindMainActivity
.MainActivitySubcomponent

有什么建议吗? :)

2 个答案:

答案 0 :(得分:1)

随着MainActivity从NetworkBaseActivity扩展而来,您只需要一个AndroidInjector即可用于MainActivity。然后将通过MainActivity注入NetworkBaseActivity。

@Module
public class NetworkActivityModule {
    @ContributesAndroidInjector(modules = { NetworkActivityModule.class })
    public abstract MainActivity bindMainActivity();    

}

答案 1 :(得分:0)

您必须注入NetworkViewModelFactory类的构造函数。构造函数应如下所示:

@Inject
public NetworkViewModelFactory(AuthRepository authRepository) { }

但是我不确定,最好也查看NetworkViewModelFactory类代码。