Hilt — A Standard Way to Implement Dependency Injection in Android

Photo by Sigmund on Unsplash

Why using Hilt?

When it comes to Dependencies Injection in Android development, we don’t have many choices:

  • Use a 3rd party library like Dagger or Koin

How to use Hilt in your Android project?

Setup

Add this Gradle dependency into the project’s root build.gradle

Hilt Application

Hilt Application is mandatory — achieved by adding the@HiltAndroidApp annotation into your Application class.

@HiltAndroidApp
class HiltSampleApp : Application() {
...
}
  • A singleton component attaches to the application lifecycle and hosts all the singleton scoped dependencies. This component also provides dependencies to all other sub-components.

Hilt Components

As I mentioned above, Hilt automatically generates some pre-defined Component classes. Those out-of-the-box components should cover most use cases when developing your Android app. We don’t need to create a Component manually anymore.

Photo on https://developer.android.com/

Declare dependencies in Hilt Modules

Similar to Dagger Module , Hilt Module is where you declare all the needed dependencies for your application.

Inject dependencies into Android classes

Now, you have done setting up theComponent and Module . It’s time to get those dependencies injected!

  • @Inject the properties like using Dagger
  • ViewModel (by using @HiltViewModel)
  • Activity
  • Fragment
  • View
  • Service
  • BroadcastReceiver

Inject dependencies into non-Android classes

Even though Hilt supports most of the Android classes, at some point, you’ll need to inject dependencies into non-supported Android classes.

Compare Hilt and Dagger

Like I mentioned from the start of this post, Hilt’s mission is to provide a standard way to apply Dagger into your application easier.

  • Application scoped Component instancing in Application class
  • Implementing HasAndroidInjector if needed
  • Injection trigger (AndroidInjection.inject(this) or Component.inject(this)
  • Activity/Service/FragmentBindingModule declaration
  • Pre-defined bindings for Android classes like Application , Activity
  • Pre-defined Qualifier like @ApplicationContext and @ActivityContext

Glasses 👓 Geek 💻 Backpacker 🎒 Climber 🧗‍♂️