Dependency injection with Hilt

Part 3 ( Hilt modules )

Noha Samir
1 min readJul 6, 2020

Sometimes a type cannot be constructor-injected. This can happen for multiple reasons. For example:

  1. You also cannot constructor-inject a type that you do not own, such as a class from an external library.
  2. You cannot constructor-inject an interface.

In these cases, you can provide Hilt with binding information by using Hilt modules.

Step 1. Inject dependencies into Android classes

We learned it in Part 2 (@AndroidEntryPoint)

Step 2. use the @Inject annotation to perform field injection

// ToDo 1 : We need to inject Glide Request manager (external library)@Inject
lateinit var glideRequestManager: RequestManager

Step 3. Create A Hilt module class that is annotated with @Module

you must annotate Hilt modules with @InstallIn to tell Hilt which Android class each module will be used or installed in. You can install it in Activity, Fragment … etc (Components)

@Module
@InstallIn(FragmentComponent::class)
class HiltModule {
...
}

Step 4. Inject instances with @Provides

you can tell Hilt how to provide instances of this type by creating a function inside a Hilt module and annotating that function with @Provides.

@Module
@InstallIn(FragmentComponent::class)
class HiltModule {
@Provides
fun provideGlide(@ActivityContext context: Context): RequestManager = Glide.with(context)

}

Note:

  1. Hilt provides some predefined qualifiers. For example, as you might need the Context class from either the application or the activity, Hilt provides the @ApplicationContext and @ActivityContext qualifiers.
  2. You should tell Hilt how to create an instance for every function parameter.

Get the code

Get the code from GitHub: (Link)

$ git clone https://github.com/NohaSamir/HiltApplication/tree/4-HiltModule

Previous parts: Part 1 / Part 2

--

--