**Dependency injection (DI), **in a nutshell, is a technique whereby one object provides or supplies the dependencies of another instead of creating it by themselves. This will let you have good architecture for your application and better code reusability.

In Android, Dagger is the dependency injection library that is recommended by Google for dependency injection. But let’s face it, there are a lot of overheads when setting up Dagger that beginners might shy away from.

This is where Dagger Hilt for Android comes in.

What is Dagger Hilt?

Hilt, built on top of Dagger, is now the new recommended DI library from Google which would help to simplify setting up Dagger in your applications.

The previous Components that we created in our app, exists now in the predefined components that are being provided to us, out of the box, by Hilt. So we won’t need to define these directly. The built-in components are also automatically integrated into the lifecycle of your app, which is really neat.

To check out these components, take a look here.

The Setup

We first need to add the following to our project level build.gradle

classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha'

Then in our module level build.gradle

apply plugin: 'dagger.hilt.android.plugin'

Finally, we can now add the required dependencies for us to use Hilt

implementation 'com.google.dagger:hilt-android:2.28-alpha'
kapt 'com.google.dagger:hilt-android-compiler:2.28-alpha'
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha01'
kapt 'androidx.hilt:hilt-compiler:1.0.0-alpha01'

When everything is synced up, we now need to annotate our application class with @HiltAndroidApp, this will generate the different Hilt components along with the base class of our application.

For our Activity/Fragment we would annotate it with@AndroidEntryPoint, this will generate the required component that will receive the dependencies that are going to be injected in our Activity/Fragment.

In cases that we have a class that has a required constructor argument

class SampleClass (val anotherSampleClass: AnotherSampleClass) {}

We can use Hilt modules to inject the required argument. Take a look at the sample below.

@Module
@InstallIn(ActivityComponent::class)
class SampleModule {

  @Provides
  fun provideAnotherSampleClass(...: ...) = AnotherSampleClass(...)
}

#dagger-hilt #android #dagger #android-app-development

A Brief Intro to Dagger Hilt
1.15 GEEK