我有一个组件 - 子组件关系。每个都有不同的范围,并使用自己的模块,提供相同类型的依赖。我需要的是基于范围的不同对象瞬时。 Dagger不允许这样做,因为我会有“多重绑定”。没有@ Named-Qualifiers我怎么解决这个问题?例如,有没有办法在子组件中覆盖?
//Higher scoped object (in component)
@Provides
@ClientScope
ISupResRankStrategy iSupResRankStrategy(@Named("GlobalModelConfig") JsonNode configSubTree,
Lazy<SortByMagnitudeSum> strat1,
Lazy<SortByShadowPercentage> strat2) {
@SuppressWarnings("rawtypes")
Map<String, Lazy> availableStrategies = new HashMap<>();
availableStrategies.put(SortByMagnitudeSum.class.getSimpleName(), strat1);
availableStrategies.put(SortByShadowPercentage.class.getSimpleName(), strat2);
String configuredStrategy = configSubTree.findValue("ISupResRankStrategy").asText();
return (ISupResRankStrategy) availableStrategies.get(configuredStrategy).get();
}
//lower scoped object (in subcomponent)
@Provides
@ModelScope
ISupResRankStrategy iSupResRankStrategy(@Named("TradeModelConfig") JsonNode configSubTree,
Lazy<SortByMagnitudeSum> strat1,
Lazy<SortByShadowPercentage> strat2) {
@SuppressWarnings("rawtypes")
Map<String, Lazy> availableStrategies = new HashMap<>();
availableStrategies.put(SortByMagnitudeSum.class.getSimpleName(), strat1);
availableStrategies.put(SortByShadowPercentage.class.getSimpleName(), strat2);
String configuredStrategy = configSubTree.findValue("ISupResRankStrategy").asText();
return (ISupResRankStrategy) availableStrategies.get(configuredStrategy).get();
}
Dagger不允许这样做,因为我会有“多重绑定”。没有@ Named-Qualifiers我怎么解决这个问题?例如,有没有办法在子组件中覆盖?
没有。您不能同时使用不同范围的2个相同类型的对象。 Dagger应该怎么知道你想要哪2个?
要拥有相同类型的多个对象
@Qualifier
,@Named
就是其中之一,但你可以用更好的名字创建自己的名字,例如: @Client
,@Model
使用@Qualifier,@ Name。你可以超载DI
例如
@Provides @Named("type1")
Model provideModel() {
return new Model();
}
@Provides @Named("type2")
Model provideModeWithContext(Context context) {
return new Model(context);
}