我刚刚学习了用于依赖注入(inject)的kodein lib。我如何才能获取变量的依赖值?
我在下面的应用程序类,在那里我用kodein绑定(bind)了上下文:
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()方法调用错误:
我如何获得上下文?这样传递上下文是个好主意吗?
最佳答案
我遇到过同样的问题。原来我缺少此依赖项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()
}
}
编辑:
这是我的项目,所有内容都连接在一起https://github.com/igorwojda/Android-Showcase