Photo by Ivan Diaz from Unsplash

Kotlin Dependency Injection with Hilt

Paul Allies
2 min readOct 22, 2021

It is encouraged that you divide your code into classes to benefit from separation of concerns, a principle where each class of the hierarchy has a single defined responsibility. This leads to more, smaller classes that need to be connected together to fulfil each other’s dependencies.

Of course, we can use good old manual dependency injection as follows:

To ease the pain of dependency injection, we are going to use Hilt to manage and resolve our dependencies.

To use Hilt, add the following build dependencies to the Android Gradle module’s build.gradle file:

plugins {
...
id 'dagger.hilt.android.plugin'
}
dependencies {
...
implementation 'com.google.dagger:hilt-android:2.39.1'
implementation 'androidx.hilt:hilt-navigation-compose:1.0.0-alpha03'
kapt "com.google.dagger:hilt-compiler:2.39.1"
kapt "androidx.hilt:hilt-compiler:1.0.0"
}

Note: you only need “hilt-navigation-compose” if you intend to inject view models

Let’s start.

  1. Make your project aware of Hilt and that's it’s going to do DI for you
  2. Mark the android activity that is going to be the root or starting point of all DI
  3. Tell Hilt how to provide instances of a ViewModel.
  4. Mark class constructors with @Inject to tell Hilt how to create instances of a class.
  5. Create your IOC container

Create Hilt Android App

All apps that use Hilt must contain an application class that is annotated with @HiltAndroidApp.

Create a file in the root package:

Update your application name in your AndroidManifest.xml file

Mark MainActivity as AndroidEntryPoint

For Hilt to be able to inject dependencies into an activity, the activity needs to be annotated with @AndroidEntryPoint. Let’s change our MainActivity from before to:

Tell Hilt about View models and Constructors

TodoView takes a default view model of TodoViewModel. This needs to be identified as aview model withconstruction injection, so we’ll have to update the view model class with @HiltViewModel annotation. Also, mark the constructor as injectable to tell Hilt to start injecting at this point.

Create IOC Container

Next, we create our container to list and resolve our dependencies.

--

--

Paul Allies
Paul Allies

Responses (1)