Hilt provides a standard way of Dagger Dependency injection to Android applications.

As some of us are already using Dagger2 for quite some time, most of them were facing a lot of issues while creating objects, dependency graphs, subcomponents creations, and their scoping and it is quite confusing if anyone uses it the first time.

Hilt came up with an approach to solve some of the problems, by using Hilt annotations will generate the dagger injection code into base classes.

Dagger Hilt Setup:

Add below code snippet in project Gradle file

Add below code snippet in app/gradle

Dagger Release notes : https://github.com/google/dagger/releases

List of Hilt annotations

@HiltAndroidapp: It starts the Hilt code generation, must be annotated for the Application class.

@AndroidEntrypoint: This annotation can use for Activities, Fragments (Hilt supports activities which extend componentactivity, fragments which extent androidx.fragment and doesn't support the retained fragment)

@Inject: Supports constructor and Field injection(Fields are not private)

you can find the field injection sampleActivity.kt above

@Provides: Return type is binding type, parameters are dependent, if the function is not scoped it generates the instance when needed.

@Module: Classes in which you can add this binding type cannot be constructor injected.

@Installin: Indicates component lifetime of module bindings, below are the different components and their lifetime

@Binds: @binds annotated methods must be abstract, parameter is the implementation type, Return type is binding type.

@Scope: Bindings in Hilt is unscoped, whenever the app requests the binding Hilt creates a new instance. However, Hilt only creates a scoped binding once per instance of the component that the binding is scoped to, and all requests for that binding share the same instance.

@ViewModelInject: How to provide an instance for architecture component ViewModel class.

@EntryPoint: Inject dependencies in classes that are not supported by Hilt. For example, Hilt doesn't support directly for Content providers, if content providers want to obtain some dependencies we can achieve it via Entrypoint annotation.

below are the components and its lifetime and its defaultbindings

Software developer @Gojek, Currently experimenting on jetpack compose.