我不太确定如何用匕首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);
然后我注入了我的活动:
ActivityModule
现在,我可以使用ApplicationModule
内声明的所有内容,但是我无法访问ApplicationModule
。
所以问题是如何实现?那么当我构建依赖于另一个组件的组件时,我仍然可以从第一个组件访问模块?
我想我已经找到了解决方案,在再次重新发送Devoxx talk by Jake之后,我不得不错过这个,不管我想要从该组件中提供的另一个组件模块中使用,例如我想要使用来自ApplicationComponent
然后在Context provideContext();
内的上下文我必须说明{{1}}并且它将可用。非常酷:))
答案 0 :(得分:15)
您已经回答了问题,但答案是在“superscoped”组件(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();
}