Reputation: 598
I have 3 components: Main app component:
@Singleton
@Component(modules = {AppModule.class, UserModule.class, DatabaseModule.class})
public interface AppComponent {
Context getContext();
DatabaseHelper getDatabaseHelper();
UserManager getUserManager();
}
Repository component:
@DataScope
@Component(dependencies = AppComponent.class, modules = CategoryRepositoryModule.class)
public interface CategoryRepositoryComponent {
CategoryRepository getCategoryRepository();
}
And screen component:
@MenuScope
@Component(dependencies = CategoryRepositoryComponent.class, modules = {MenuModule.class, DrawerModule.class})
interface MenuComponent {
void inject(MenuActivity activity);
}
The problem is that my MenuComponent cannot see dependencies that provides AppComponent. But MenuComponent depend on CategoryRepositoryComponent and CategoryRepositoryComponent depend on AppComponent, so MenuComponent should see AppComponent(MenuComponent -> CategoryRepositoryComponent -> AppComponent).
If I will add getters to CategoryRepositoryComponent
@DataScope
@Component(dependencies = AppComponent.class, modules = CategoryRepositoryModule.class)
public interface CategoryRepositoryComponent {
CategoryRepository getCategoryRepository();
DatabaseHelper getDatabaseHelper();
UserManager getUserManager();
}
But thats looks incorrect, duplicates. Do you know how to resolve this problem in a clean, correct way?
Thanks, Nick.
Upvotes: 3
Views: 1321
Reputation: 3162
Your approach is correct. Components only have access to the types explicitly exposed by their direct parent component.
This can be useful when, as a parent, you don't want to expose all of your dependencies to whoever depends on you. For example, a Parent
may depend on a BankComponent and not want to expose BankAccount
to its Children
.
An alternative approach is to use Subcomponent
. The docs and this other answer will help understand: Dagger 2 subcomponents vs component dependencies.
Upvotes: 4