skip to content

In Dagger, how do component dependencies differ from a @Subcomponent, and which bindings can each one see?

level: middleimportance: should knowfreq 40%

answer

  1. inherit everything vs see an interface
  2. generated inside the parent
  3. only provision methods cross over
  4. Module.subcomponents installs a child
  5. parents never see children

basics

~20 s

A @Subcomponent is generated inside its parent and inherits the parent's entire binding graph. A component that lists another type in its dependencies is generated separately and sees only the provision methods that type exposes.

solid answer

~40 s

A `@Subcomponent` is tightly coupled: Dagger generates it inside the parent's implementation, it can use any binding of its parent and ancestors, and you install it by listing it in `@Module(subcomponents = [...])` on a parent module, which binds its `Factory` or `Builder` in the parent. A component dependency is looser: `@Component(dependencies = [CoreComponent::class])` produces its own `Dagger`-prefixed class, each provision method on `CoreComponent` becomes a binding, and nothing else crosses over; you pass the `CoreComponent` instance into the factory. In both cases the parent never sees the child's bindings. I reach for subcomponents for nested lifetimes inside one graph, and for component dependencies when a feature must compile its own component against an interface, such as an on-demand feature module the base app cannot depend on.

code

kotlin · 60 lines
kotlin
import dagger.Component
import dagger.Module
import dagger.Provides
import dagger.Subcomponent
import javax.inject.Inject
import javax.inject.Scope
import javax.inject.Singleton

@Scope @Retention(AnnotationRetention.RUNTIME) annotation class CheckoutScope
@Scope @Retention(AnnotationRetention.RUNTIME) annotation class ReceiptScope

class HttpClientFactory
class ApiClient(val factory: HttpClientFactory)

// :core module
@Module
object CoreModule {
    @Provides @Singleton fun httpClientFactory(): HttpClientFactory = HttpClientFactory()
    @Provides @Singleton fun apiClient(factory: HttpClientFactory): ApiClient = ApiClient(factory)
}

@Singleton
@Component(modules = [CoreModule::class])
interface CoreComponent {
    fun apiClient(): ApiClient // the only binding dependents can see
}

// :feature-checkout module, compiled against the CoreComponent interface
@CheckoutScope
class Cart @Inject constructor(val api: ApiClient)

@ReceiptScope
class ReceiptPrinter @Inject constructor(val cart: Cart)

@Module(subcomponents = [ReceiptComponent::class])
object CheckoutModule

@CheckoutScope
@Component(dependencies = [CoreComponent::class], modules = [CheckoutModule::class])
interface CheckoutComponent {
    fun cart(): Cart
    fun receiptComponentFactory(): ReceiptComponent.Factory

    @Component.Factory
    interface Factory {
        fun create(core: CoreComponent): CheckoutComponent
    }
}

// A child of CheckoutComponent: sees every binding CheckoutComponent has
@ReceiptScope
@Subcomponent
interface ReceiptComponent {
    fun receiptPrinter(): ReceiptPrinter

    @Subcomponent.Factory
    interface Factory {
        fun create(): ReceiptComponent
    }
}

go deeper

for a junior

Recall the one-line difference: a subcomponent inherits everything from its parent, while a component dependency sees only the other component's provision methods.

for a middle

Explain how each is installed and created, Module.subcomponents with an injected factory versus a dependency instance passed into a factory, and which direction bindings flow.

for a senior

Diagnose a missing binding across a component-dependency boundary, and apply the scope rules: no ancestor's scope in a child, and scoped dependencies only for scoped components.

for a principal

Weigh coupling against isolation in a large modular app: subcomponents keep the graph in one place, component dependencies let a feature compile alone against an interface.

## Two ways to relate Dagger components A real app needs more than one graph: objects that live as long as the process, objects that live for a signed-in session, objects that live for one screen. Dagger gives you two mechanisms for connecting a smaller graph to a larger one, and they differ in **what the smaller graph can see** and **where its code is generated**. | | `@Subcomponent` | Component dependency | |---|---|---| | Declared with | `@Subcomponent`, installed via `@Module(subcomponents = [...])` or a factory method on the parent | `@Component(dependencies = [CoreComponent::class])` | | Generated as | Part of the parent component's implementation | Its own `Dagger`-prefixed class | | Sees from the other graph | Every binding of the parent and all ancestors | Only the provision methods of the dependency type | | Created by | Asking the parent for its `Factory` or `Builder` | Passing the dependency instance to its factory or builder | | Validated | Only once attached to a parent | On its own | ## Subcomponents inherit the whole parent graph A **subcomponent** is declared like a component but annotated `@Subcomponent`, usually with a nested `@Subcomponent.Factory` or `@Subcomponent.Builder`. Its rules: - An object bound in a subcomponent may depend on **anything bound in its parent or any ancestor**, plus its own modules. - The parent **cannot** depend on bindings from its subcomponents, and **sibling** subcomponents cannot see each other's bindings. - Because it inherits the parent's graph, a subcomponent is **not checked for completeness until it is attached** to a parent. - A subcomponent may add contributions to a multibound set or map from its parent; those extra entries are visible only inside the subcomponent and its descendants. There are two ways to install one. Listing it in `@Module(subcomponents = [SessionComponent::class])` on a module the parent installs binds `SessionComponent.Factory` in the parent, so any parent binding can inject the factory. Alternatively the parent component declares an abstract method returning the subcomponent or its builder. The Dagger guide prefers the module attribute, because Dagger can then tell whether the subcomponent is ever requested; a factory method on the parent is an explicit request and forces generation even if nobody calls it. ## Component dependencies expose only an interface With `@Component(dependencies = [CoreComponent::class])`, Dagger treats the dependency type, usually another component's interface, as a source of bindings: **each provision method on it is bound as a provider**, and only those. If `CoreComponent` uses an `HttpClientFactory` internally but does not declare `fun httpClientFactory(): HttpClientFactory`, the dependent component cannot inject it. - The dependent component is a **separate generated class** compiled against the dependency's interface, not its implementation. - Its factory or builder **must** take an instance of each dependency, for example `fun create(core: CoreComponent): CheckoutComponent`. - Changing what crosses the boundary means editing the dependency's interface, which makes the contract explicit. ## Scopes across the two mechanisms Scopes tie a binding's single instance to one component instance, and both mechanisms have rules about them: 1. A subcomponent may not use the **same scope as any ancestor**. Two siblings may share a scope annotation, because each holds its own instances. 2. A component that depends on a **scoped** component must itself be scoped; Dagger reports an `(unscoped) cannot depend on scoped components` error otherwise. 3. A `@Singleton` component **cannot depend on scoped components** at all, since `@Singleton` stands for the longest lifetime. ## Choosing between them in a modular app - **Subcomponents** fit nested lifetimes inside one graph: an application component with a session subcomponent with screen subcomponents. Children reuse parent bindings without any boilerplate. The cost is coupling: the parent's generated code contains the children, so the root's compilation must see every subcomponent and its modules. - **Component dependencies** fit boundaries where the larger graph must not know the smaller one. The classic Android case is an on-demand feature module: the base app cannot depend on it, so the feature declares its own component that depends on a core component interface and compiles it locally. - **Encapsulation** works with both. A subcomponent can keep implementation bindings, such as a connection pool, private to itself while exposing one result to the parent through a `@Provides` method that builds the subcomponent. How those scopes map onto an app's logout or account-switch lifecycle is an architecture question for the modularization material; the mechanism here is only how Dagger links the graphs and what each side can see.

  • With Dagger component dependencies, the dependent component fails to find a binding that the core component clearly uses internally: why?
    Only the dependency type's provision methods cross the boundary. A binding the core component uses to build its own objects is invisible to dependents unless the core interface declares a method returning it, such as `fun httpClientFactory(): HttpClientFactory`. Add that method, or rethink whether the dependent should construct that object at all.
  • In Dagger, why may two sibling subcomponents share a scope annotation while a child may not reuse its parent's scope?
    A scoped binding is stored in the component that carries the scope. Siblings are never ancestors of each other, so each holds its own instances and there is no ambiguity. A child reusing an ancestor's scope would leave Dagger unable to say which component owns the instance, so it is a compile error.
  • Why does the Dagger guide prefer installing a subcomponent through @Module(subcomponents = ...) over an abstract method on the parent component?
    The module attribute lets Dagger see whether anything actually requests the subcomponent's factory or builder. A method on the parent component counts as an explicit request even if it is never called, so Dagger must generate the subcomponent regardless.

  • A dependent component can inject any binding the other component has internally.
  • A parent component can inject bindings defined in its subcomponents.
  • Sibling subcomponents share bindings because they share a parent.
  • A subcomponent must reuse its parent's scope annotation.
  • A subcomponent is validated on its own before any parent installs it.