Hilt
Android Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project. It 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.
Dependency injection in Android
DI is a technique through which we can create required objects outside the class and provide those objects to a class. In big application project, classes are dependent of other classes. In programming, we achieve this connection between classes by creating objects. Dependency injection helps make these connections and enables you to swap out implementations for testing
Advantages of DI :
- Code Reusability
- Ease of testing
- Refactoring
Adding dependencies
Add plugin in project’s root build.gradle
1 2 3 4 5 6 7 |
buildscript { ... dependencies { ... classpath 'com.google.dagger:hilt-android-gradle-plugin:2.28-alpha' } } |
Add dependencies in your app/build.gradle
file:
1 2 3 4 5 6 7 8 9 10 11 12 |
... apply plugin: 'kotlin-kapt' apply plugin: 'dagger.hilt.android.plugin' android { ... } dependencies { implementation "com.google.dagger:hilt-android:2.28-alpha" kapt "com.google.dagger:hilt-android-compiler:2.28-alpha" } |
Hilt application class
All apps that use Hilt must contain an Application
class that is annotated with @HiltAndroidApp
. In Hilt, we don’t need to create a component, include every module, and build for generating DaggerAppComponent class. We can inject instance of app into other module in Hilt.
1 2 |
@HiltAndroidApp class MyApplicationClass : Application() |
Hilt modules
A Hilt module is a class that is annotated with @Module
. Like a Dagger module, it informs Hilt how to provide instances of certain types. You must annotate Hilt modules with @InstallIn
to tell Hilt which Android class each module will be used or installed in.
Example : You wanna Hilt to inject that dependency into your Activity class.
1 2 3 4 5 |
@Module @InstallIn(ActivityComponent::class) object MyModuleClass{ } |
To know more about Dependency Injection, check following link : Dependency Injection