首页 > 解决方案 > 不能使用注入值作为另一个注入的构造函数

问题描述

我想定义 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:未找到定义。检查您的模块定义。

标签: androidkotlindependency-injectionkoin

解决方案


好的,我遇到了两个问题,首先我无法在构造函数中使用其他 bean 实例化 bean,通过将调用更改为

        ConnectionServiceTcp(
            get<ResourcesHelper>().getConfigValueAsString(ResourcesHelper.droneAddressPropertyName),
            get<ResourcesHelper>().getConfigValueAsInt(ResourcesHelper.dronePortPropertyName)
        )

其次,NoBeanDefFoundException 有问题,它是androidContext()在 ResourcesHelperImpl 中引起的,我需要来自活动的上下文,而不是 koin 上下文。


推荐阅读