Dependency Injection (Dagger 2) in Android App
Dagger 2 generates DI code at compile time—no reflection, no runtime surprises. You pay for this: component graphs, scopes, subcomponents, and qualifiers require understanding the architecture before you start. Chaotic Dagger setup in the middle of a project—one of the most painful refactorings in Android development.
Component Structure
Standard scheme for large app: AppComponent (Singleton) → ActivityComponent (PerActivity) → FragmentComponent (PerFragment). Each level—subcomponent or dependent component.
@Singleton
@Component(modules = [AppModule::class, NetworkModule::class, DatabaseModule::class])
interface AppComponent {
fun inject(app: App)
fun activityComponentBuilder(): ActivityComponent.Builder
}
@Module
class NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder()
.addInterceptor(AuthInterceptor())
.connectTimeout(30, TimeUnit.SECONDS)
.build()
}
@Provides
@Singleton
fun provideRetrofit(client: OkHttpClient): Retrofit {
return Retrofit.Builder()
.baseUrl(BuildConfig.API_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
Scopes and Their Boundaries
Most common mistake—wrong scopes. If UserRepository is declared @Singleton and AuthToken inside is stored in memory, then after logout without component recreation, the old token remains in the live object. This leads to requests with someone else's token—production bug that reproduces only with specific usage scenario.
Solution: @Singleton components should not contain mutable state dependent on user session. Session-dependent dependencies are moved to @UserScope:
@Scope
@Retention(AnnotationRetention.RUNTIME)
annotation class UserScope
@UserScope
@Subcomponent(modules = [UserModule::class])
interface UserComponent {
@Subcomponent.Factory
interface Factory {
fun create(@BindsInstance userId: String): UserComponent
}
fun inject(profileFragment: ProfileFragment)
}
UserComponent is created after login, destroyed after logout. All user-dependent dependencies live exactly as long as needed.
Multibindings and Plugin Architecture
@Module
abstract class ViewModelModule {
@Binds
@IntoMap
@ViewModelKey(LoginViewModel::class)
abstract fun bindLoginViewModel(vm: LoginViewModel): ViewModel
@Binds
@IntoMap
@ViewModelKey(ProfileViewModel::class)
abstract fun bindProfileViewModel(vm: ProfileViewModel): ViewModel
}
@IntoMap with @ViewModelKey—pattern for ViewModel injection via ViewModelProvider.Factory. Dagger creates Map<Class<out ViewModel>, Provider<ViewModel>>, factory selects the needed class. Without this pattern, each ViewModel must be declared separately in the component.
Kapt and KSP
Dagger 2 traditionally works with kapt. Starting from Dagger 2.50, experimental KSP support is available, which accelerates incremental builds. For new projects it makes sense to use KSP:
// build.gradle.kts
plugins {
id("com.google.devtools.ksp")
}
dependencies {
implementation("com.google.dagger:dagger:2.51")
ksp("com.google.dagger:dagger-compiler:2.51")
}
On a project with ~200 Dagger annotations, switching from kapt to KSP reduced clean build time from 4.5 to 2.8 minutes.
Testing
Dagger and tests—separate story. Standard approach: test modules that replace production dependencies with fakes:
@Component(modules = [TestNetworkModule::class, DatabaseModule::class])
interface TestAppComponent : AppComponent
@Module
class TestNetworkModule {
@Provides
@Singleton
fun provideApiService(): ApiService = FakeApiService()
}
In Espresso tests DaggerTestAppComponent is substituted for the main one in App.appComponent before test run. Without this replacement, integration tests go to the real server.
When to Choose Dagger 2 vs Hilt
Hilt—wrapper over Dagger with predefined component structure. If you need non-standard scopes, multi-module graph with independent components, or Dagger already in project—Dagger 2 gives full control. Hilt starts faster but limits in complex architectures.
Setting up Dagger 2 from scratch—3–5 days: architecture analysis, component graph design, module setup, ViewModel integration. Refactoring existing code to Dagger—from one week. Cost is calculated individually.







