我刚刚学习了用于依赖注入的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()”
我如何获得背景信息?像这样传递上下文是个好主意吗?
答案 0 :(得分:0)
我有同样的问题。原来我缺少此依赖项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
)。这样,创建Fragment时将解决debug
构建的所有依赖关系,因此应用程序将立即失败(与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()
}
}