Member-only story
Android Interview Question Answer: Dependency Injection with Hilt
What is Dependency Injection (DI)?
Dependency injection (DI) is a technique that allows objects to receive dependencies from external sources, rather than creating them internally in class definition.
What is the use of dependency injection in android.
DI helps to make code maintainable and testable.
Different types of Dependency Injection?
- Constructor Injection: Dependencies are passed via the constructor.
- Field Injection: Dependencies are assigned directly to fields.
- Method Injection: Dependencies are passed via setter methods
Can we use DI without using any framework
Yes, manually passing dependencies through constructors of class but this becomes difficult as the app size grows.
What is Hilt in Android ?
Hilt is a dependency injection library for Android that reduces the boilerplate of doing manual dependency injection in your project.
Can you describe how to set up Hilt in an Android project?
step 1: Add required dependencies to build.gradle
step 2: Create an Application Class and Annotate with @HiltAndroidApp
also set it in the Android manifest.
step 3: Create a Module to Provide Dependencies