android - 不能使用注入值作为另一个注入的构造函数
问题描述
我想定义 2 个注入的类,但需要为构造函数使用第二种类方法。我正在使用 Koin 框架
class MainActivity : AppCompatActivity() {
private val connectionService : ConnectionService by inject()
private val resourcesHelper : ResourcesHelper by inject()
private val addressPropertyName = "connection.address"
private val portPropertyName = "connection.port"
private val appModule = module {
single { ResourcesHelperImpl(androidContext(), R.raw.config) }
single {
ConnectionServiceTcp(
resourcesHelper.getConfigValueAsString(addressPropertyName),
resourcesHelper.getConfigValueAsInt(portPropertyName)
)
}
}
然后我收到一个错误,因为我无法使用 resourcesHelper 实例化 ConnectionServiceTcp。有没有办法使用注入的字段来注入另一个字段?
编辑更改为 get() 有所帮助,但现在我在模块配置方面遇到了困难。我将 start koin 移至 MainApplication 类:
class MainApplication : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@MainApplication)
androidLogger()
modules(appModule)
}
}
}
和模块到 AppModule.kt
val appModule = module {
single { ResourcesHelperImpl(androidContext(), R.raw.drone) }
single {
ConnectionServiceTcp(
get<ResourcesHelper>().getConfigValueAsString(ResourcesHelper.droneAddressPropertyName),
get<ResourcesHelper>().getConfigValueAsInt(ResourcesHelper.dronePortPropertyName)
)
}
scope(named<MainActivity>()) {
scoped {
ConnectionServiceTcp(get(), get())
}
}
}
然后我尝试向活动注入一些对象,但我得到了原因:org.koin.core.error.NoBeanDefFoundException:未找到定义。检查您的模块定义。
解决方案
好的,我遇到了两个问题,首先我无法在构造函数中使用其他 bean 实例化 bean,通过将调用更改为
ConnectionServiceTcp(
get<ResourcesHelper>().getConfigValueAsString(ResourcesHelper.droneAddressPropertyName),
get<ResourcesHelper>().getConfigValueAsInt(ResourcesHelper.dronePortPropertyName)
)
其次,NoBeanDefFoundException 有问题,它是androidContext()
在 ResourcesHelperImpl 中引起的,我需要来自活动的上下文,而不是 koin 上下文。
推荐阅读
- python - Python:如何创建依赖于实例中其他属性的属性
- multithreading - JNI 环境中 pthread_cond_broadcast() 和 pthread_cond_timedwait() 的等效函数是什么?
- c# - LEFT AND RIGHT 函数 lambda 表达式 c#
- google-cloud-platform - 如何在重复值列中检索 5 个最大数字?
- apache-spark - 如果在读取数据时,Spark 的 partitionColumn 中不存在 upperBound 和 lowerBound 的值怎么办?
- laravel - 当模型在 Laravel 中作为关系删除时,观察者删除不起作用
- sass - 从子 scss 调用父级
- sql - SQL 列名是一个数据,并且反透视不起作用
- python - 使用 scipy 进行约束根查找
- reactjs - 为什么我的 React 预算应用程序在计算总数、使用 setState 更新状态然后将其渲染到 UI 时会出现延迟?