Updated 30 July 2020
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.
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 :
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" } |
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() |
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
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.