问题
Dagger 2是否可以使用带有片段(@ContributesAndroidInjector)子组件的子组件的树形结构?如果是这样,如何将映射的Android Injector暴露给对象图(Dagger-android)?
背景
我试图创建一个树状的组件结构,以避免必须在应用程序中将对象引用从一个类传递到另一个类。为此,我尝试查看Dagger 2子组件文档以创建层次结构,但是由于文档混乱/丢失,我无法创建要实现的功能。
我包括一个经过深思熟虑的体系结构的模型:
Application
|
| @ApplicationScope
| ApplicationComponent
---------------------------------------------------------------------------------------------
| |
@ActivityScope @ActivityScope
DiscussionsActivity ChatActivity
------------------------------------- ------------
| |
@FragmentScope @CategoryScope
DiscussionsCategoryListFragment CategoryComponent
------------------------------- -------------------------------------
| |
@FragmentScope @TopicScope
DiscussionsTopicListFragment TopicComponent
---------------------------- ---------------------------------------------
| |
@FragmentScope @FragmentScope
DiscussionsTopicDetailsFragment DiscussionsTopicCommentsFragment
我还为那些需要视觉表示设计的人添加了一个设计模型。
Design Mockup
代码
public class MyApplication extends DaggerApplication {
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent
.builder()
.application(this)
.build();
}
}
@ApplicationScope
@Component(modules = {
ActivityBindingModule.class,
AndroidSupportInjectionModule.class,
})
public interface AppComponent extends AndroidInjector<MyApplication> {
@Component.Builder
interface Builder {
@BindsInstance
Builder application(Application application);
AppComponent build();
}
}
@Module
public abstract class ActivityBindingModule {
@ContributesAndroidInjector(modules = {
DiscussionActivityModule.class,
DiscussionActivityFragmentBindingModule.class,
})
abstract DiscussionActivity contributesDiscussionActivity();
}
@Module(subcomponent = CategoryComponent.class)
public abstract class DiscussionActivityModule {
// How should I do to get the Fragments contributed in the
// CategoryComponent and its subcomponent included in the AndroidInjector factory?
}
@Module
public abstract class DiscussionActivityFragmentBindingModule {
@FragmentScope
@ContributesAndroidInjector(modules = DiscussionsCategoryListFragmentModule.class)
abstract DiscussionsCategoryListFragment contributesDiscussionsCategoryListFragment();
}
@CategoryScope
@Subcomponent(modules = {
CategoryFragmentBindingModule.class,
}
public interface CategoryComponent {
@Subcomponent.Builder
interface Builder {
Builder categoryModule(@Category long categoryId);
CategoryComponent build();
}
}
@Module
public abstract class CategoryFragmentBindingModule {
// How do I make this map entry available for the
// Map<Class<? extends Fragment>, AndroidInjector.Factory<? extends Fragment>> fragmentInjector factory?
@FragmentScope
@ContributesAndroidInjector(modules = DiscussionsTopicListFragmentModule.class)
abstract DiscussionsTopicListFragment contributesDiscussionsTopicListFragment();
}
好的,所以我可以包括更多代码,或根据要求解释当前的内容。
EDIT1:固定错字。