Dependency injection with Hilt-3(Modules)
Sometimes a type cannot be constructor-injected. This can happen for multiple reasons. For example, you cannot constructor-inject an interface. You also cannot constructor-inject a type that you do not own, such as a class from an external library. In these cases, you can provide Hilt with binding information by using Hilt modules.
Outline :
- Fit to be used in interfaces
- Easy to use with external library
- There are two types of modules, which we use both in this example code (Binds and Provides)
Let’s check it out!!
Scope :
Create an interface
interface MyInterface {
fun myPrintFunction() : String
}
Create a class for implementing interface with inject constructor
class InterfaceImplementor
@Inject constructor() : MyInterface {
override fun myPrintFunction(): String {
return "My interface Implementor"
}
Create a class for using MainActivity
//Gson is an external library
class ClassExample
@Inject constructor
(private val myInterfaceImplementor: MyInterface,
private val gson : Gson)
{
fun myFunction() : String {
return "Working: ${myInterfaceImplementor.myPrintFunction()}"
}
Usage :
1.Inject interface instances with Binds
You have to use abstract class for using Binds
@InstallIn(ActivityComponent::class)
@Module
abstract class MyModule{
@ActivityScoped
@Binds
abstract fun bindingFunction(myImplementor: InterfaceImplementor):MyInterface
}
2. Inject instances with Provides
- No need to use abstracts
- Useable for working with external library
- Easier than Binds
@InstallIn(SingletonComponent::class)
@Module
class MyModule{
@Singleton
@Provides
fun providerFunction():MyInterface{
return InterfaceImplementor()
}
Result :
@Inject
lateinit var myClass : ClassExampleoverride fun onCreate(...
println(myClass.myFunction())//Logcat
System.out: working...
System.out: My interface Implementor
Finally we will look at Annotation and finish this series of hilt..