Dagger-2:如何根据其范围为同一对象类型创建不同的实例化?

问题描述 投票:0回答:2

我有一个组件 - 子组件关系。每个都有不同的范围,并使用自己的模块,提供相同类型的依赖。我需要的是基于范围的不同对象瞬时。 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();
}
java dependency-injection dagger-2
2个回答
1
投票

Dagger不允许这样做,因为我会有“多重绑定”。没有@ Named-Qualifiers我怎么解决这个问题?例如,有没有办法在子组件中覆盖?

没有。您不能同时使用不同范围的2个相同类型的对象。 Dagger应该怎么知道你想要哪2个?

要拥有相同类型的多个对象

  • 使用@Qualifier@Named就是其中之一,但你可以用更好的名字创建自己的名字,例如: @Client@Model
  • 使用组件依赖项而不是子组件,这样就不能将对象公开给依赖组件,从而允许自己的实例

0
投票

使用@Qualifier,@ Name。你可以超载DI

例如

 @Provides @Named("type1") 
  Model provideModel() {
  return new Model();
  }

 @Provides @Named("type2") 
 Model provideModeWithContext(Context context) {
 return new Model(context);
   }
© www.soinside.com 2019 - 2024. All rights reserved.