Dependency injection inside extension function

Viewed 1029

Is there a way to inject an object inside an extension function or a global function using DI framework in Android Kotlin?

I use this function in many places. So I do not want to pass a parameter every time.

DI framework can be any of Koin, Hilt, Dagger2, or others.

Something like that:

fun Context.showSomething() {
 val myObject = inject()
 showToast(myObject.text)
}
2 Answers

Instead of thinking about using Inject you could pass it as a parameter:

fun Context.showSomething(myObject: String) {
 showToast(myObject.text)
}

With Koin you can do like this,

fun Context.showSomething() {
  val myObject = GlobalContext.get().get()
  showToast(myObject.text)
}

but it's totally not recommended way of using it.

Related