Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 10]

Mastering Hilt - Android | Kotlin | Hilt (Dagger 2) [Part 10]

Becoming Proficient in Dependency Injection with Hilt for Android (Kotlin)

ยท

2 min read

Migration from Dagger to Hilt

Migrating from Dagger to Hilt is a straightforward process, as Hilt is built on top of Dagger and designed to simplify the dependency injection setup in Android apps.

Here's a step-by-step guide on how to migrate from Dagger to Hilt:

Step 1: Remove Dagger Dependencies

Before migrating to Hilt, remove all the existing Dagger dependencies from our project's build.gradle file:

// Remove Dagger dependencies
implementation 'com.google.dagger:dagger:2.x.x'
kapt 'com.google.dagger:dagger-compiler:2.x.x'

Step 2: Add Hilt Dependencies

Add the Hilt dependencies to our project's build.gradle file:

// Add Hilt dependencies
implementation 'com.google.dagger:hilt-android:2.40.5'
kapt 'com.google.dagger:hilt-android-compiler:2.40.5'

Step 3: Add Hilt Plugin

Apply the Hilt plugin in our app module's build.gradle file:

apply plugin: 'kotlin-kapt'
apply plugin: 'dagger.hilt.android.plugin'

Step 4: Convert Application Class

Change our Application class to extend HiltAndroidApp instead of Application:

@HiltAndroidApp
class MyApplication : Application() {
    // Application code
}

Step 5: Replace Component Annotations

Replace Dagger's @Component and @Module annotations with Hilt's corresponding annotations:

Before:

@Component(modules = [MyModule::class])
interface MyComponent {
    // Component methods
}

After:

@Module
@InstallIn(SingletonComponent::class)
object MyModule {
    // Module methods
}

@EntryPoint
@InstallIn(SingletonComponent::class)
interface MyEntryPoint {
    // Entry point methods
}

Step 6: Replace Injection Annotations

Replace Dagger's @Inject annotation with Hilt's corresponding annotations in Activities, Fragments, and other classes:

Before:

class MyActivity : AppCompatActivity() {
@Inject
lateinit var myDependency: MyDependency
    // Activity code
}

After:

@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
@Inject
lateinit var myDependency: MyDependency
    // Activity code
}

Step 7: Migrate Hilt Modules

Migrate our Dagger modules to Hilt modules. Most of the migration involves changing the annotations, and the code remains largely the same.

Step 8: Update Test Classes

Update our test classes to use Hilt's testing annotations if we were previously using Dagger's testing annotations:

Before (Dagger):

@PerActivity
class MyActivityTest {
    // Test code
}

After (Hilt):

@HiltAndroidTest
class MyActivityTest {
    // Test code
}

That's it! That's how we can start our journey to the migration of Dagger to Hilt. The migration process is quite seamless, and Hilt's simplified annotations and integration with Android components make it easier to work with dependency injection in Android apps.


That's it for this series. Happy Coding...

ย