Dependency Injection with Dagger or Hilt in Android Development
Dependency Injection (DI) is a design pattern used to reduce coupling in code by providing objects their dependencies rather than creating them internally. Dagger and Hilt are popular DI frameworks for Android development. This article explains the basics of dependency injection using Dagger and Hilt with examples in Kotlin.
Introduction to Dagger
Dagger is a fully static, compile-time dependency injection framework. It requires you to define modules, components, and injectable objects explicitly.
Example
// Define a class to inject class NetworkService { fun fetchData(): String = "Data from Network" } // Define a module @Module class NetworkModule { @Provides fun provideNetworkService(): NetworkService { return NetworkService() } } // Define a component @Component(modules = [NetworkModule::class]) interface AppComponent { fun inject(activity: MainActivity) } // Use the injected dependency class MainActivity : AppCompatActivity() { @Inject lateinit var networkService: NetworkService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val appComponent = DaggerAppComponent.create() appComponent.inject(this) println(networkService.fetchData()) } }
Introduction to Hilt
Hilt is a dependency injection library built on top of Dagger and designed to simplify DI in Android. It reduces boilerplate code and integrates seamlessly with the Android lifecycle.
Example
// Add the Hilt annotations @HiltAndroidApp class MyApplication : Application() // Define a class to inject class NetworkService { fun fetchData(): String = "Data from Network" } // Define a Hilt module @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides fun provideNetworkService(): NetworkService { return NetworkService() } } // Use the injected dependency @AndroidEntryPoint class MainActivity : AppCompatActivity() { @Inject lateinit var networkService: NetworkService override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) println(networkService.fetchData()) } }
Why Choose Hilt over Dagger?
- Hilt automatically provides integration with Android components like Activities, Fragments, and ViewModels.
- It reduces the need to define custom components and explicit inject calls.
- Hilt provides better support for scoping and lifecycle management in Android apps.
Conclusion
Both Dagger and Hilt are powerful tools for implementing dependency injection in Android. While Dagger offers fine-grained control, Hilt simplifies the process and is better suited for most modern Android apps. Choosing the right framework depends on your project requirements and preferences.