Dagger: Component, Module & @Inject
Dagger 2 is a fully static, compile-time dependency injection framework for Java/Kotlin and Android. Rather than resolving dependencies via reflection at runtime, it generates plain, readable dependency-wiring code at compile time -- both faster and able to catch configuration errors as build errors, not runtime crashes.
@Inject: Classes Dagger Can Construct Directly
// A class you've written yourself -- Dagger can inspect its
// constructor directly, no separate @Provides method needed
class UserRepository @Inject constructor(
private val apiClient: ApiClient,
)Modules: Constructing What Dagger Can't Figure Out Alone
// Third-party classes (Retrofit) -- Dagger has no visibility into
// their constructor, so a Module explicitly shows how to build one
@Module
class NetworkModule {
@Provides
@Singleton // ONE shared instance for the Component's lifetime,
// not a fresh one every time it's requested
fun provideRetrofit(): Retrofit =
Retrofit.Builder().baseUrl(BASE_URL).build()
}
// @Binds: tells Dagger which implementation to use for an interface --
// more efficient than an equivalent @Provides that manually constructs it
@Module
abstract class RepositoryModule {
@Binds
abstract fun bindUserRepository(impl: UserRepositoryImpl): UserRepository
}Components: The Generated Bridge
@Component(modules = [NetworkModule::class, RepositoryModule::class])
interface AppComponent {
fun inject(activity: MainActivity)
}
// Dagger generates DaggerAppComponent.kt at BUILD time -- open it in
// your IDE to see the actual, readable constructor-calling logic when
// debugging a confusing DI errorKeep your own version of these notes — editable, searchable, and organised by your stack.
Start free