skip to content

Dagger

Dagger 2 generates and validates the dependency graph at compile time from components, subcomponents and bindings, so a wiring mistake fails the build. Asked as the engine beneath Hilt.

on this pageshow

explore

questions

6

In Dagger 2, what does an @Inject constructor tell the compiler, and what does a @Component interface give your Android app?

level: juniorimportance: must knowfreq 55%

answer

  1. a recipe read at build time
  2. constructor parameters become dependencies
  3. interface in, Dagger-prefixed class out
  4. provision vs members-injection methods
  5. factory with @BindsInstance

basics

~20 s

An @Inject constructor tells Dagger how to build a class and which dependencies it needs first. A @Component interface is the graph's entry point: Dagger generates a Dagger-prefixed implementation that wires every binding and fails the build when one is missing.

solid answer

~40 s

Putting `@Inject` on a constructor registers a binding: Dagger may call that constructor, and it must satisfy every parameter first. Types you cannot annotate, such as an interface, a third-party class or the `Application`, come from `@Provides` methods in a `@Module` or from a `@BindsInstance` parameter on the component's factory. A `@Component` interface lists its modules and declares entry points: provision methods like `fun settingsRepository(): SettingsRepository`, and members-injection methods like `fun inject(activity: MainActivity)` for objects the framework constructs. At build time the annotation processor generates `DaggerAppComponent`, validates the whole graph and turns a missing binding into a compile error instead of a runtime crash. You usually create it once in `Application.onCreate` or a lazy property, for example `DaggerAppComponent.factory().create(this)`.

code

kotlin · 50 lines
kotlin
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import dagger.BindsInstance
import dagger.Component
import dagger.Module
import dagger.Provides
import javax.inject.Inject
import javax.inject.Singleton

@Module
object StorageModule {
    @Provides
    fun provideSettingsPrefs(app: Application): SharedPreferences =
        app.getSharedPreferences("settings", Context.MODE_PRIVATE)
}

@Singleton
class SettingsRepository @Inject constructor(
    private val prefs: SharedPreferences,
) {
    fun isOnboarded(): Boolean = prefs.getBoolean("onboarded", false)
}

@Singleton
@Component(modules = [StorageModule::class])
interface AppComponent {
    fun settingsRepository(): SettingsRepository // provision method
    fun inject(activity: MainActivity)             // members-injection method

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance app: Application): AppComponent
    }
}

class App : Application() {
    val appComponent: AppComponent by lazy { DaggerAppComponent.factory().create(this) }
}

class MainActivity : AppCompatActivity() {
    @Inject lateinit var settings: SettingsRepository

    override fun onCreate(savedInstanceState: Bundle?) {
        (application as App).appComponent.inject(this)
        super.onCreate(savedInstanceState)
    }
}

go deeper

for a junior

Recall the three binding sources, @Inject constructor, @Provides in a module and @BindsInstance, and the two kinds of component method: provision and members injection.

for a middle

Explain what the generated DaggerAppComponent does, when it exposes factory(), builder() or create(), and why an Activity uses members injection instead of constructor injection.

for a senior

Show you know where the graph gets validated, why errors land at the component, and the members-injection covariance trap that leaves subclass fields empty in production.

for a principal

Be ready to weigh compile-time graphs against runtime resolution: build-time cost and a fixed graph in exchange for no reflection and errors caught before release.

## What `@Inject` on a constructor declares Dagger is a **compile-time dependency injection** framework: an annotation processor reads your annotations during the build and generates plain Java code that constructs your objects. The smallest unit it understands is a **binding**, a rule for producing one type. The most common way to declare a binding is to annotate a class's constructor with `@Inject` (the standard `javax.inject.Inject` annotation). That one annotation says two things: - **Dagger may build this class** by calling this constructor whenever something asks for the type. - **Each constructor parameter is a dependency** that Dagger must satisfy first, using some other binding. So `class SettingsRepository @Inject constructor(private val prefs: SharedPreferences)` means: to produce a `SettingsRepository`, first produce a `SharedPreferences`. Dagger follows those edges recursively and builds a **binding graph**. ## Where bindings come from when you cannot annotate a constructor You cannot put `@Inject` on an interface, on a class from a library, or on something the platform hands you. Dagger has other ways to declare those bindings: | Source of the binding | When you use it | |---|---| | `@Inject` constructor | Your own concrete classes | | `@Provides` method in a `@Module` | Interfaces, library types, anything built by a factory call | | `@BindsInstance` on the component's factory or builder | Runtime objects you already hold, such as the `Application` | A **module** is a class or Kotlin `object` annotated with `@Module` whose methods produce values. A component only uses the modules it lists in `@Component(modules = [...])`, plus the modules those modules `include`. ## What a `@Component` is A **component** is an interface or abstract class annotated with `@Component`. It is the boundary of a graph and the place where your code asks for objects. Its abstract methods come in two shapes: 1. **Provision methods** take no parameters and return a type, for example `fun settingsRepository(): SettingsRepository`. They may also return `Provider<T>` or `Lazy<T>`. 2. **Members-injection methods** take one parameter and fill its `@Inject`-annotated fields and methods, for example `fun inject(activity: MainActivity)`. Android normally constructs an `Activity` itself, so Dagger cannot call its constructor; the activity calls `inject(this)` and receives its `@Inject lateinit var` fields. Dagger does not support injection into private fields. A members-injection method injects the members of its parameter type and that type's supertypes, not those of subclasses. `inject(activity: BaseActivity)` called with a `MainActivity` leaves the fields declared on `MainActivity` empty. ## The generated class and how you create it For `@Component interface AppComponent`, Dagger generates `DaggerAppComponent`. How you instantiate it depends on what the component needs from you: - With a nested `@Component.Factory`, the generated class has a static `factory()`; you call its single method with every required argument, for example `DaggerAppComponent.factory().create(application)`. All factory parameters are required. - With a nested `@Component.Builder`, the generated class has `builder()`, and you call setters and then `build()`. - With neither, Dagger generates a builder with one setter per module and component dependency. - When the component needs nothing passed in, no component dependencies, no bound instances and only modules Dagger can instantiate itself, it also gets a static `create()`. A component may declare a `Factory` or a `Builder`, not both. `@BindsInstance` marks a factory parameter or builder setter whose argument becomes a binding inside the graph, which is how an `Application` or a `Context` usually enters a plain-Dagger graph. ## Why the compile-time part matters Because the whole graph is analysed during the build, mistakes surface early: - A type nobody can provide fails the build with a `[Dagger/MissingBinding]` error that names the missing key and the chain of requests that needed it. - A dependency cycle, a scope mismatch or a duplicate binding is likewise a compile error, not a crash on some rarely opened screen. - The generated code is ordinary method calls and constructor calls, so there is no reflection at runtime and a stack trace walks through readable generated classes. The cost is that the graph is fixed at compile time: you cannot add a binding at runtime, and every change to the graph means a recompile through the annotation processor. In an Android app the usual shape is one application-wide component created once and stored on the `Application` subclass, with shorter-lived components hanging off it for screens or sessions. Hilt automates that shape on Android; in plain Dagger you write the components, their factories and the `inject` calls yourself.

  • Why does an Activity get a members-injection method rather than an @Inject constructor in a plain-Dagger app?
    On the normal path the Android framework, not Dagger, instantiates an `Activity` through its no-argument constructor, so Dagger never gets to call a constructor with dependencies. Instead the component declares `fun inject(activity: MainActivity)`, the activity calls it early in `onCreate`, and Dagger assigns every non-private `@Inject` field such as `@Inject lateinit var settings: SettingsRepository`.
  • A Dagger component declares inject(activity: BaseActivity) and you pass a MainActivity: which @Inject fields get set?
    Only the `@Inject` members declared on `BaseActivity` and its supertypes. A members-injection method works from its declared parameter type, so fields declared on `MainActivity` stay uninitialised and a `lateinit` access later throws. Declare `fun inject(activity: MainActivity)` for each concrete class that has its own injected fields.
  • When does a Dagger-generated component expose a static create() method?
    When the component needs nothing from the caller: no component dependencies, no `@BindsInstance` values, and only modules Dagger can instantiate itself or does not need an instance of. Then `DaggerAppComponent.create()` is equivalent to building it with no arguments. Once the factory takes an `Application`, you must go through `factory().create(app)`.

An @Inject constructor is a recipe card listing its ingredients; the component is the kitchen that, before opening, checks that every dish on its menu can be made from what is stocked, and refuses to open if one cannot.

  • Dagger resolves the graph at runtime by reflection, like a service locator.
  • Every class needs a @Provides method even when it has an @Inject constructor.
  • You implement the @Component interface yourself by hand.
  • A missing binding shows up as a crash when the screen first opens.
  • An inject(base: BaseActivity) method also fills a subclass's own @Inject fields.
open as a page

In Dagger, how do injecting T, Provider<T> and Lazy<T> differ, and how does a scope annotation change what each returns?

level: middleimportance: must knowfreq 45%

basics

~20 s

Injecting T resolves the value at injection time; Provider<T> resolves again on every get(); Lazy<T> resolves on the first get() and caches it in that one Lazy. A scope annotation makes the binding return one instance per component instance, whichever form requests it.

open as a page

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

level: middleimportance: should knowfreq 40%

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.

open as a page

In Dagger, how do @AssistedInject and @AssistedFactory build an object that needs both graph dependencies and a runtime argument, and what restrictions apply?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Mark the constructor @AssistedInject and each runtime parameter @Assisted, then declare an @AssistedFactory interface whose one method takes those parameters. Dagger implements and binds the factory; you inject the factory, never the type, and the type cannot be scoped.

open as a page

A plain-Dagger Android build fails: how do you read a [Dagger/MissingBinding], [Dagger/IncompatiblyScopedBindings] or [Dagger/DependencyCycle] error back to its cause?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Read the bracketed check name, the reported key, then the trace from that key to the component entry point. A missing binding needs a provider in that component, a scope error a matching component scope, a cycle a Provider, a Lazy or a redesign.

open as a page

In a modular Android app on plain Dagger, how do @IntoMap and a map key let feature modules contribute ViewModel providers to one factory?

level: seniorimportance: nice to knowfreq 25%

basics

~20 s

Each feature module adds one entry with an @IntoMap binding plus a key annotation such as @ClassKey; Dagger assembles a Map<Class<*>, Provider<ViewModel>> that a single ViewModelProvider.Factory injects and looks up by class, without knowing any feature.

open as a page