Dependency Injection with Hilt in Android Kotlin

Dependency Injection is one of the common term most of the developers use.

Earlier in android, developers were using manual dependency injection. Later Dagger and Dagger2 introduced, which is now maintained by Google. Dagger is one of the popular dependency injection library which is available. But if you have tried dagger, it’s a little bit complicated to set up initially.

So google came up with a new library called HILT. HILT is built on top of Dagger to benefit from the compile-time correctness, runtime performance, scalability, and Android Studio support that Dagger provides. Hilt came up with following properties on top of Dagger.

  • To simplify Dagger-related infrastructure for Android apps.
  • To create a standard set of components and scopes to ease setup, readability, and code sharing between apps.
  • To provide an easy way to provision different bindings to various build types, such as testing, debug, or release.

So In this section I am going to explain you how to integrate Hilt Inside your application in kotlin.

First step is to install hilt-android-gradle-plugin to your project’s root build.gradle file

then apply this plugin add your dependencies to app/build.gradle file

Hilt uses Java 8 features.So add java8 compatibility also like above.

Now you are ready with the setup.

Next step is to annotate application class.All apps that use Hilt must contain an Application class that is annotated with @HiltAndroidApp.

Next step is to annotate activity.Once Hilt is set up in your Application class and an application-level component is available, Hilt can provide dependencies to other Android classes that have the @AndroidEntryPoint annotation:

If you annotate an Android class with @AndroidEntryPoint, then you also must annotate Android classes that depend on it. For example, if you annotate a fragment, then you must also annotate any activities where you use that fragment.

To obtain dependencies from a component,use the @Inject annotation

Hilt modules

For a project where you have retrofit and apiservice,you can define an ApiModule class and add @Module annotation,And for making that class singleton use @SingletonComponent::class

Like this you can define your apimodule class.

By doing this the project is ready with hilt dependency injection

if you want to provide any other class,you can define as submodule class and add @Provides annotation.

Hilt more easier to implement,and code readability is more easy.

That’s all for now..

Happy Coding … Happy Reading …



Passionate android developer working with android mobile and androidTv

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
yadunath narayanan

Passionate android developer working with android mobile and androidTv