扩展函数内的依赖注入



是否有办法在Android Kotlin中使用DI框架注入扩展函数或全局函数中的对象?

我在很多地方使用这个函数。所以我不想每次都传递一个参数。

DI框架可以是Koin、Hilt、Dagger2或其他。

像这样:

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

不考虑使用Inject,您可以将其作为参数传递:

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

使用Koin,您可以这样做,

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

但是完全不推荐这样使用

我使用我的应用程序组件注入到扩展方法。例如,要在扩展方法中使用MyInjectableClass:

// 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!
}

当然,您仍然需要为MyInjectableClass提供@Provides@Binds方法。

最新更新