Middle+
How to perform interface injection in Dagger?
sobes.tech AI
Answer from AI
To perform interface injection in Dagger, you need to provide a concrete implementation for it using @Binds or @Provides.
-
@Binds: Preferred method if the implementation is a class that Dagger can directly instantiate (e.g., with an
@Injectconstructor).interface MyInterface { fun doSomething() } class MyInterfaceImpl @Inject constructor() : MyInterface { override fun doSomething() { // ... implementation } } @Module interface MyModule { @Binds fun bindMyInterface(impl: MyInterfaceImpl): MyInterface } -
@Provides: Used when the implementation requires more complex creation logic, such as using a third-party library or configuration.
interface AnotherInterface { fun getData(): String } class AnotherInterfaceImpl : AnotherInterface { private val someValue: String constructor(value: String) { someValue = value } override fun getData(): String { return someValue } } @Module object AnotherModule { @Provides fun provideAnotherInterface(): AnotherInterface { // Complex creation logic return AnotherInterfaceImpl("some data") } }
Then, the Dagger component should include these modules:
@Component(modules = [MyModule::class, AnotherModule::class])
interface AppComponent {
fun inject(activity: MyActivity)
// ...
}
Now, in the class where the interface needs to be injected, simply declare a field with the @Inject annotation:
class MyActivity : AppCompatActivity() {
@Inject
lateinit var myInterface: MyInterface
@Inject
lateinit var anotherInterface: AnotherInterface
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
(application as MyApplication).appComponent.inject(this)
myInterface.doSomething()
val data = anotherInterface.getData()
// ...
}
}