Concepts and Jetpack Compose implementation
Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. Doing manual dependency injection requires you to construct every class and its dependencies by hand, and to use containers to reuse and manage dependencies.
Hilt provides a standard way to use DI in your application by providing containers for every Android class in your project and managing their lifecycles automatically. Hilt is built on top of the popular DI library Dagger to benefit from the compile-time correctness, runtime performance, scalability, and Android Studio support that Dagger provides. For more information, see Hilt and Dagger.
This guide explains the basic concepts of Hilt and its generated containers. It also includes a demonstration of how to bootstrap an existing app to use Hilt.
Hilt application class
All apps that use Hilt must contain an
Application class that is annotated with
@HiltAndroidApp.
@HiltAndroidApp triggers Hilt's code generation, including a base class for
your application that serves as the application-level dependency container.
Kotlin
@HiltAndroidApp class ExampleApplication : Application() { ... }
Java
@HiltAndroidApp public class ExampleApplication extends Application { ... }
This generated Hilt component is attached to the Application object's
lifecycle and provides dependencies to it. Additionally, it is the parent
component of the app, which means that other components can access the
dependencies that it provides.
Inject dependencies into Android classes
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:
Kotlin
@AndroidEntryPoint class ExampleActivity : AppCompatActivity() { ... }
Java
@AndroidEntryPoint public class ExampleActivity extends AppCompatActivity { ... }
Hilt currently supports the following Android classes:
Application(by using@HiltAndroidApp)ViewModel(by using@HiltViewModel)ActivityFragmentViewServiceBroadcastReceiver
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.
@AndroidEntryPoint generates an individual Hilt component for each Android
class in your project. These components can receive dependencies from their
respective parent classes as described in Component
hierarchy.
To obtain dependencies from a component, use the @Inject annotation to perform
field injection:
Kotlin
@AndroidEntryPoint class ExampleActivity : AppCompatActivity() {