【问题标题】:Dagger 2 - modules from different componentsDagger 2 - 来自不同组件的模块
【发布时间】:2015-03-18 18:44:46
【问题描述】:

我不太清楚如何用匕首 2 解决这个问题。 假设我们有ApplicationModule 为我们提供ApplicationContext 然后我们有ApplicationComponent 只使用这个模块。 然后在它之上我们有ActivityModuleActivityComponent 依赖于ApplicationComponentActivityComponent 的构建就像

    ApplicationComponent component = ((MyApplication) getApplication()).getComponent();

    mComponent = Dagger_ActivityComponent.builder()
            .applicationComponent(component)
            .activityModule(new ActivityModule(this))
            .build();

然后我注入我的活动:

mComponent.inject(this);

现在我可以使用ActivityModule 中声明的所有内容,但是我无法访问ApplicationModule

那么问题是如何实现呢?这样当我构建依赖于另一个组件的组件时,我仍然可以从第一个组件访问模块?

编辑

我想我已经找到了解决方案,在再次重看Devoxx talk by Jake 之后,我不得不错过这一点,无论我想从另一个组件模块中使用什么,我必须在该组件中提供,例如我想使用 Context from ApplicationModule 然后在 ApplicationComponent 里面我必须声明 Context provideContext(); 并且它将可用。很酷:)

【问题讨论】:

标签: android dagger-2


【解决方案1】:

您已经回答了您的问题,但答案是在您的“超作用域”组件(ApplicationComponent)中指定提供方法。

例如,

@Module
public class ApplicationModule {
    @Provides
    @Singleton
    public Something something() {
        return new Something.Builder().configure().build(); 
           // if Something can be made with constructor, 
           // use @Singleton on the class and @Inject on the constructor
           // and then the module is not needed
    }
}

@Singleton
@Component(modules={ApplicationModule.class})
public interface ApplicationComponent {
    Something something(); //PROVISION METHOD. YOU NEED THIS.
}

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface ActivityScope {
}

@ActivityScope
public class OtherThing {
    private final Something something;

    @Inject
    public OtherThing(Something something) {
        this.something = something;
    }
}

@Component(dependencies = {ApplicationComponent.class})
@ActivityScope
public interface ActivityComponent extends ApplicationComponent { //inherit provision methods
    OtherThing otherThing();
}

【讨论】:

  • 需要extends ApplicationComponent吗?
  • @mbmc 您这样做是为了继承提供方法(即Something something();)-如果您不继承,那么我认为您将无法子范围 ActivityComponent if你永远需要它。
  • 看来设置依赖就足够从父组件访问provision方法了。
  • @mbmc 你是对的,在 Activity 组件中设置依赖项(App 组件)将允许后者注入任何范围内要在 Activity 上使用的东西。
  • 找不到注释@ActivityScope
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-17
  • 2015-10-28
  • 2017-03-22
  • 1970-01-01
相关资源
最近更新 更多