Dependency Injection With Hilt Android

Gaya's techtips
1 min readSep 10, 2023

When I looking to guides for jetpack compose I saw that there are library called Hilt and it useful to do dependency injection in android. I’m going to summarize what I learned from there in brief.

As very first step you need to add following code lines in project level gradle file.

Then you have to add following codes in app level gradle file

these libraries are add functionalities for hilt dependency injection and jetpack compose navigation as well. I thought that I can get clear idea with multiple UI’s so I create some simple UI’s named as Login and Register.

first you have to annotate android app as hilt android app.

@HiltAndroidApp
class MainApplication @Inject constructor() : Application(){

}

then you have to add it to manifest file using name in application tag. I added MainApplication as name because my annotated application’s child class name is MainApplication

<manifest ....>
<application
android:name=".MainApplication"
...
>
...
</application>
</manifest>

then you have to define some entry point for dependency injection and it should be activity component. I added this codeline in MainActivity.kt file

@AndroidEntryPoint //Newly Added Codeline
class MainActivity : ComponentActivity() {
...
}

Then you can design your viewmodel and user interface as well.

Then you can create hilt view model

@HiltViewModel
class MainScreenViewModel @Inject constructor(
//TODO:Injected services from hilt dependency injection
):ViewModel(){
//TODO:your content
}

then you can create jetpack compose UI

@Preview()
@Composable
fun MainScreen(
viewModel : MainScreenViewModel = hiltViewModel()
){
//TODO:your content goes here....
}

then you can connect with jetpack compose navigation to main activity

--

--