我有一个带有一些参数的演示者。
public WidgetPresenterImpl(WidgetSettingInteractor stateInteractor,
WidgetStatisticInteractor statisticApiInteractor,
WidgetStatisticInteractor statisticCacheInteractor,
Context context) {
mStateInteractor = stateInteractor;
mStatisticApiInteractor = statisticApiInteractor;
mStatisticCacheInteractor = statisticCacheInteractor;
mContext = context;
}
演示者的初始化看起来像这样
WidgetPresenter presenter = new WidgetPresenterImpl(
new WidgetSettingInteractorImpl(new WidgetRepositoryImpl()),
new WidgetStatisticInteractorImpl(new WidgetStatisticApiRepositoryImpl()),
new WidgetStatisticInteractorImpl(new WidgetStatisticCacheRepositoryImpl()),
context);
我想用匕首进行初始化。为此,我写了一个模块
@Module
public abstract class WidgetModule {
@Binds
abstract WidgetPresenter widgetPresenter(WidgetPresenterImpl presenter);
@Binds
abstract WidgetSettingInteractor widgetSettingInteractor(WidgetSettingInteractorImpl settingInteractor);
@Binds
abstract WidgetStatisticInteractor widgetStatisticInteractor(WidgetStatisticInteractorImpl statisticInteractor);
@Binds
abstract WidgetStatisticRepository widgetStatisticApiRepository(WidgetStatisticApiRepositoryImpl apiRepository);
@Binds
abstract WidgetStatisticRepository widgetStatisticCacheRepository(WidgetStatisticCacheRepositoryImpl cacheRepository);
@Binds
abstract WidgetRepository widgetSettingRepository(WidgetRepositoryImpl widgetRepository);
}
但项目不会,错误
error: [dagger.android.AndroidInjector.inject(T)] ....WidgetStatisticRepository is bound multiple times:
@Binds ....WidgetStatisticRepository ....widgetStatisticApiRepository(....WidgetStatisticApiRepositoryImpl)
@Binds ....WidgetStatisticRepository ....widgetStatisticCacheRepository(....WidgetStatisticCacheRepositoryImpl)
答案 0 :(得分:0)
根据评论似乎不需要这样做,但考虑到后续问题,您可能会对此有所帮助。这可能是这样的:
@Named("Api")
@Binds
abstract WidgetStatisticRepository
widgetStatisticApiRepository(WidgetStatisticApiRepositoryImpl apiRepository);
@Named("Cache")
@Binds
abstract WidgetStatisticRepository
widgetStatisticCacheRepository(WidgetStatisticCacheRepositoryImpl cacheRepository);
然后你可以简单地在WidgetPresenterImpl的构造函数中添加@Inject注释(假设你有一个@Provides方法返回一个Context):
@Inject
public WidgetPresenterImpl(WidgetSettingInteractor stateInteractor,
@Named("Api") WidgetStatisticInteractor statisticApiInteractor,
@Named("Cache") WidgetStatisticInteractor statisticCacheInteractor,
Context context) {
mStateInteractor = stateInteractor;
mStatisticApiInteractor = statisticApiInteractor;
mStatisticCacheInteractor = statisticCacheInteractor;
mContext = context;
}
或者假设您想要抽象WidgetPresenter接口的实现,您可以在非抽象模块中创建相应的@Provides方法:
@Module
class WidgetPresenterModule {
@Provides
public WidgetPresenter provideWidgetPresenter(WidgetSettingInteractor stateInteractor,
@Named("Api") WidgetStatisticInteractor statisticApiInteractor,
@Named("Cache") WidgetStatisticInteractor statisticCacheInteractor,
Context context) {
return new WidgetPresenterImpl(stateInteractor, statisticApiInteractor, statisticCacheInteractor, context);
}
}