【发布时间】:2019-11-12 00:10:38
【问题描述】:
我想定义 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:未找到定义。检查您的模块定义。
【问题讨论】:
-
你试过这个
single {ConnectionServiceTcp(get<ResourcesHelper>().getConfigValueAsString(addressPropertyName)...}吗?另外,我认为您应该将模块移动到单独的文件中,并将startKoin移动到Application类中。
标签: android kotlin dependency-injection koin