Dependency Injection with Dagger 2 in Android app

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.
Development and support of all types of mobile applications:
Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1 servicesAll 1735 services
Dependency Injection with Dagger 2 in Android app
Medium
~3-5 business days
FAQ
Our competencies:
Development stages
Latest works
  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    756
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    624
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1052
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    947
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    862
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    445

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.