3

我刚刚学习了依赖注入的kodein lib。我如何获取变量的依赖值?我的应用程序类在下面,我将上下文与 kodein 绑定:

class BaseApp : Application(), KodeinAware {
    override val kodein by Kodein.lazy {
        import(contextModule)
    }

    private val contextModule = Kodein.Module(CONTEXT_MODULE_TAG){
        bind<Context>(CONTEXT_TAG) with provider { this@BaseApp }
    }

    companion object{
        private const val CONTEXT_MODULE_TAG = "context_module"
        const val CONTEXT_TAG = "context_tag"
    }
}

在我的存储库类中,我尝试获取上下文,但没有成功。

class BatteryRepository : KodeinAware {
    override val kodein by kodein()
    private val context by instance<Context>(BaseApp.CONTEXT_TAG)
...

其中kodein()方法调用错误:

表达式“kodein”不能作为函数调用。未找到函数“invoke()”

我怎样才能获得上下文?像这样转移上下文是个好主意吗?

4

1 回答 1

5

我遇到过同样的问题。原来我错过了这个依赖import org.kodein.di.android.x.kodein(不知道为什么它没有被 IDE 自动添加)

这是Kodein+AndroidX库的示例:AndroidManifest.xml

<application
        ...
        android:name=".core.BaseApplication">

应用

open class BaseApplication : Application(), KodeinAware {
    override val kodein = Kodein.lazy {
        import(androidXModule(this@BaseApplication))

        // import(otherCustomModule)
    }
}

碎片

import androidx.fragment.app.Fragment
import org.kodein.di.Kodein
import org.kodein.di.KodeinAware
import org.kodein.di.android.x.kodein
import org.kodein.di.generic.kcontext

abstract class InjectionFragment : Fragment(), KodeinAware {

    final override val kodeinContext = kcontext<Fragment>(this)
    final override val kodein: Kodein by kodein()


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        kodeinTrigger?.trigger()
    }
}

// usage
class MyFragment() : InjectionFragment() {
    val someDependency: Type by instance()
}

依赖项app\build.gradle

implementation "org.kodein.di:kodein-di-generic-jvm:6.3.2"
implementation "org.kodein.di:kodein-di-framework-android-x:6.3.2"
implementation "androidx.appcompat:appcompat:1.0.2"

额外kodeinTrigger重写属性(来自) 也是值得的KodeinAware。这样,debug在创建 Fragment 时,构建的所有依赖项都将得到解决,因此应用程序将立即失败(与release仅在使用时才解决依赖项的构建相反 - 某些用户路径可能不会使应用程序崩溃)

abstract class InjectionFragment : Fragment(), KodeinAware {

    final override val kodeinContext = kcontext<Fragment>(this)
    final override val kodein: Kodein by kodein()
    final override val kodeinTrigger: KodeinTrigger? // See description in InjectionActivity
        get() = if (BuildConfig.DEBUG) KodeinTrigger() else super.kodeinTrigger

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        kodeinTrigger?.trigger()
    }
}

编辑:这是我的项目,所有东西都连接在一起https://github.com/igorwojda/Android-Showcase

于 2019-06-28T12:45:10.780 回答