3

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)
}

3 Answers 3

1

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

fun Context.showSomething(myObject: String) {
 showToast(myObject.text)
}
Sign up to request clarification or add additional context in comments.

2 Comments

I use this function in many places. So I do not want to pass a parameter every time.
There is very little choice but to either pass in a parameter, or put this method on a class that is constructed instead of on a top-level extension.
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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.