Koin Kotlin - 如何在 Activity 之外使用 inject/get

Koin Kotlin - How to use inject/get outside of Activity

我目前正在尝试将 Koin 实施到我的 Android 应用程序中。它在我可以访问 get()inject() 的活动中运行良好,但在 类 之外我无法使用它们。

例如,我有一个名为 Device 的非常简单的 class,它只会创建用户设备的对象。我需要在其中获取对 MyStorage 的引用。

data class Device(
    val username: String,
    ...
) {

    companion object {

        fun get(): Device {
            val storage: MyStorage = get() // does not work

            val username = storage.username

            return Device(
                username,
                ...
            )
        }
    }
}

但是 get() 在此 class 中不起作用,手动添加导入也无济于事。

我也看到了这个答案,,它扩展了 KoinComponent,但在这种情况下或我已经 运行 进入的其他情况下不起作用,例如 top- class.

之外的级别函数

如有任何提示,我们将不胜感激。谢谢。

好吧,我也会考虑通过依赖注入制作 Device 对象,它可以接受 MyStorage 在构造函数中注入。

val appModule = module {

    factory { Device(get()) }    // MyStorage injected using get()

}

但如果它不适合您的需要,请尝试从 ComponentCallbacks 对象(例如从 Application)获取 MyStorage

class App : Application() {

    companion object {
        private lateinit var instance: App

        fun get(): App = instance
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    fun getMyStorage(): MyStorage {
        return get()
    }
}

fun get(): Device {
    val storage: MyStorage = App.get().getMyStorage()

    ...
}