16

我不太确定如何用 dagger 2 解决这个问题。假设我们有ApplicationModule它提供给我们,ApplicationContext 那么我们有ApplicationComponent它只使用这个模块。然后在它之上,我们拥有ActivityModule并且ActivityComponent依赖于ApplicationComponent. ActivityComponent构建就像

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

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

然后我注入我的活动:

mComponent.inject(this);

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

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

编辑

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

4

1 回答 1

16

您已经回答了您的问题,但答案是在您的“超范围”组件(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();
}
于 2015-08-25T21:49:35.713 回答