How to use Dagger 2 in an Android app?

Dagger 2 is a powerful dependency injection framework for Java and Android that helps manage your application's dependencies in a clean and efficient way. Here's a basic overview of how to integrate Dagger 2 into your Android app.

Step 1: Add Dagger Dependencies

First, you need to add the Dagger 2 dependencies to your app's build.gradle file:

dependencies { implementation 'com.google.dagger:dagger:2.x' // Replace x with the latest version kapt 'com.google.dagger:dagger-compiler:2.x' // For Kotlin projects }

Step 2: Create Your Modules

Modules are classes where you define methods that provide dependencies.

@Module class AppModule { @Provides fun provideContext(application: Application): Context { return application.applicationContext } @Provides fun provideNetworkService(): NetworkService { return NetworkService() } }

Step 3: Create Your Components

Components are interfaces that connect the modules and the classes that need dependencies.

@Component(modules = [AppModule::class]) interface AppComponent { fun inject(application: MyApplication) fun inject(activity: MainActivity) }

Step 4: Initialize Dagger in Your Application Class

Initialize the Dagger component in your Application class:

class MyApplication : Application() { lateinit var appComponent: AppComponent override fun onCreate() { super.onCreate() appComponent = DaggerAppComponent.builder() .appModule(AppModule()) .build() } }

Step 5: Inject Dependencies in Activities or Fragments

Finally, you can inject dependencies into your activities or fragments:

class MainActivity : AppCompatActivity() { @Inject lateinit var networkService: NetworkService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) (application as MyApplication).appComponent.inject(this) // Now you can use networkService } }

Dagger 2 Dependency Injection Android DI Dagger Setup Android Development