Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 104 ยท Dependency Injection

Dagger 2 Fundamentals

Learn Dagger 2: @Inject constructors, @Component, @Module with @Provides and @Binds, scopes, subcomponents and why Hilt wraps Dagger. Includes a hand-written component to run.

Hilt is the recommended way to do dependency injection on Android, but Hilt is not a separate engine. It is a set of conventions and predefined components built on top of Dagger 2. Hilt generates Dagger components for you and attaches them to Android classes. When you read a Hilt error such as [Dagger/MissingBinding], or when you open an older codebase that wires Dagger by hand, you are looking at Dagger. Knowing it makes Hilt less magical, and it explains the rules Hilt enforces.

Dagger 2 is a compile-time dependency injection framework. An annotation processor reads your annotations, builds a graph of who needs what, verifies that every dependency can be provided, and generates ordinary Java code that creates your objects. There is no reflection at run time and no container to configure, which makes it fast, and wiring mistakes fail the build.

The real annotations need the Android build chain, so the Dagger code in this lesson is read-only. The TryIts are plain Kotlin stand-ins: a hand-written component that does what Dagger would generate, and a small graph checker that reports missing bindings the way the compiler does.

Setup in one look

Dagger runs as an annotation processor. With Kotlin the long-standing option is kapt; newer Dagger versions also support KSP, so check the Dagger documentation for what your version recommends.

Kotlin
// read-only example: app/build.gradle.kts
plugins {
    alias(libs.plugins.kotlin.kapt)
}
dependencies {
    implementation("com.google.dagger:dagger:2.57")
    kapt("com.google.dagger:dagger-compiler:2.57")
}

@Inject: telling Dagger how to build a class

Annotate a class's constructor with @Inject, and Dagger knows how to create it, and that it needs whatever the constructor's parameters are.

Kotlin
// read-only example: needs Dagger
class NotesRepository @Inject constructor(
    private val api: NotesApi,
    private val dao: NotesDao,
)

class NotesViewModel @Inject constructor(
    private val repository: NotesRepository,
) : ViewModel()

That is constructor injection, the same idea as in Dependency Injection Concepts. @Inject can also mark fields (@Inject lateinit var analytics: Analytics) for classes the system creates, such as activities, but the field is set by a call you make yourself (component.inject(this)), and it is public and mutable, so prefer constructors whenever you can.

@Component: the graph's entry point

A component is an interface that describes what the graph can give you. Dagger generates the implementation, named Dagger + the interface name.

Kotlin
// read-only example: needs Dagger
@Component(modules = [NetworkModule::class, DatabaseModule::class])
interface AppComponent {
    fun notesViewModelFactory(): NotesViewModelFactory   // a "provision" method
    fun inject(activity: MainActivity)                   // a "members injection" method

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

// in Application.onCreate()
val component: AppComponent = DaggerAppComponent.factory().create(this)

A provision method returns an object from the graph. A members-injection method like inject(MainActivity) fills the @Inject fields of an object you already have. @BindsInstance puts an object you already hold (here the Application) into the graph.

Modules: @Provides and @Binds

You cannot add @Inject to classes you do not own (Retrofit, Room), or to an interface. A module is a class that tells Dagger how to get those.

Kotlin
// read-only example: needs Dagger
@Module
object NetworkModule {
    @Provides
    @Singleton
    fun retrofit(): Retrofit =
        Retrofit.Builder().baseUrl("https://api.example.com/")
            .addConverterFactory(GsonConverterFactory.create()).build()

    @Provides
    fun notesApi(retrofit: Retrofit): NotesApi = retrofit.create(NotesApi::class.java)
}

@Module
interface RepositoryModule {
    @Binds
    fun bindNotes(impl: RoomNotesRepository): NotesRepository   // interface -> implementation
}

@Provides is a function with a body that builds the object; its parameters come from the graph. @Binds is an abstract function that says "when someone needs the interface, give them this implementation" and generates no extra code, so it is cheaper than a @Provides that just returns its argument. The class on the right must itself be injectable (an @Inject constructor or another binding).

Two bindings for the same type are ambiguous. Disambiguate with a qualifier: your own annotation marked @Qualifier, or the built-in @Named("io").

Scopes: one instance per component

By default Dagger creates a new instance every time a dependency is requested. A scope annotation changes that: an object annotated with a scope is created once per component instance and reused.

Kotlin
// read-only example: needs Dagger
@Singleton
class TokenStore @Inject constructor()          // one per AppComponent

@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class FeatureScope                    // your own scope

@FeatureScope
class CartState @Inject constructor()           // one per FeatureComponent

@Singleton is just the built-in scope. A scope is not magic: "singleton" means "one per instance of the component that carries that annotation". If you build two AppComponents, you get two "singletons". The component interface must be annotated with the same scope as the classes it caches, and Dagger fails the build if a longer-lived scope depends on a shorter-lived one.

Subcomponents: a graph inside a graph

A subcomponent inherits all bindings of its parent and adds its own, with a shorter life. Use one for a logged-in session or a feature flow:

Kotlin
// read-only example: needs Dagger
@FeatureScope
@Subcomponent(modules = [CheckoutModule::class])
interface CheckoutComponent {
    fun cartState(): CartState

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

@Module(subcomponents = [CheckoutComponent::class])
object AppSubcomponents

The parent exposes CheckoutComponent.Factory; you create a checkout component when the flow starts and drop it when the flow ends, which frees every @FeatureScope object with it. The child can see the parent's TokenStore, but the parent cannot see the child's CartState. A dependent component (dependencies = [...]) is the older alternative that sees only what the parent explicitly exposes.

What a component really is

Strip away the annotations and Dagger's generated component is a class with a provider for each type, caching those that are scoped. This TryIt writes that by hand for a tiny graph, so you can see where "one per component" comes from.

Kotlin A hand-written component (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last line is the scope lesson in one result: the DAO is shared inside one component and is distinct across components.

Dagger tells you when the graph is incomplete

Because Dagger analyzes the graph at build time, a missing or duplicate binding stops the build with a message that names the chain of requests. The second stand-in models this with a tiny binding registry and a checker that walks the graph.

Kotlin A graph checker (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The real messages are longer and print the component and binding sites, but the principle is the same: read the chain from the top.

Dagger versus Hilt

Dagger 2 Hilt
Components You design and write them Predefined for Android: SingletonComponent, ActivityRetainedComponent, ViewModelComponent, ActivityComponent and more
Entry into Android classes You call component.inject(activity) yourself @AndroidEntryPoint does it
ViewModels Hand-written factories @HiltViewModel plus hiltViewModel()
Flexibility Maximum, including multi-module and custom lifetimes Opinionated, less boilerplate
Typical use Large legacy apps, non-Android Kotlin and Java New Android apps

Hilt exists because most apps wrote the same Dagger setup over and over. When Hilt's fixed component tree does not fit your design, drop down to Dagger; the knowledge in this lesson carries over directly. For new Android projects, start with Hilt and reach for plain Dagger only for a specific need.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does Dagger find out that a dependency is missing?

    Dagger is a compile-time framework. It verifies the whole graph during annotation processing and fails the build with the chain of requests.
  2. 2. What is the difference between @Provides and @Binds?

    Use @Provides for classes you cannot annotate or that need construction code. Use @Binds to bind an interface to an injectable implementation, which generates less code.
  3. 3. A class annotated @Singleton is requested from two different AppComponent instances. How many instances exist?

    A scope means one instance per instance of the component that carries it. Two components have two separate 'singletons'.
  4. 4. Why use a subcomponent for a checkout flow?

    A subcomponent has a shorter lifetime than its parent. Dropping the component frees all objects scoped to it.
  5. 5. What is the main reason Hilt exists?

    Hilt generates Dagger code with predefined Android components and annotations such as @AndroidEntryPoint and @HiltViewModel.

Summary

  • Dagger 2 builds your object graph at compile time with an annotation processor, with no reflection, and fails the build when a binding is missing, duplicated or cyclic.
  • @Inject constructors teach Dagger how to build your classes; @Module with @Provides and @Binds covers classes you do not own and interfaces.
  • A @Component is the entry point; Dagger generates DaggerAppComponent, and provision or members-injection methods expose what the graph can give.
  • Without a scope every request makes a new object; a scope means one instance per instance of its component.
  • Subcomponents add a shorter-lived graph on top of a parent's bindings, for sessions and flows.
  • Hilt is Dagger plus predefined Android components and entry points; use Hilt for new apps, and Dagger when you need custom component design.

Next: Testing ViewModels