2

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)
}
Yeldar Nurpeissov
  • 1,786
  • 14
  • 19

3 Answers3

1

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

fun Context.showSomething(myObject: String) {
 showToast(myObject.text)
}
DoctorWho
  • 1,044
  • 11
  • 34
0

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.

Aleksei Potapkin
  • 1,021
  • 12
  • 23
0

I use my app component to inject into extension methods. For example, to use MyInjectableClass in an extension method:

// Your app component
@Component
interface ApplicationComponent {
    fun myInjectable(): MyInjectableClass
}

// Your app class
class MyApplication: Application() {
    companion object {
        var appComponent: ApplicationComponent? = null
    }

    override fun onCreate() {
        appComponent = DaggerAppComponent.create()
    }
}

// Ext.kt file

private val injectable: MyInjectableClass?
    get() = MyApplication.appComponent?.myInjectable()

fun Foo.extension() {
    injectable?.bar()
    // huzzah!
}

Of course you still need to provide the @Provides or @Binds method for MyInjectableClass.

Barry Fruitman
  • 12,316
  • 13
  • 72
  • 135