如何使用koin依赖库在模块中注入活动上下文

时间:2019-05-16 20:24:40

标签: android dependency-injection dagger koin

我有一个下面的Util模块,它需要活动上下文[不是应用程序上下文]来执行其某些功能。

如何将活动上下文注入其中?

class MainPresenter internal constructor(private val iMainActivity: IActivity)  : IPresenter {

    //dependencies
    private val context = iMainActivity as AppCompatActivity

    private var util = UtilModule(context)         //<-- inject this
    private var httpClient = HttpClient(context)   //<-- inject this

2 个答案:

答案 0 :(得分:1)

在这种情况下,正如@commonsware所说,presenter类依赖于活动是不好的。 注入的更好解决方案可能类似于以下结构:

class IActivity{

    private val utilModule: UtilModule by lazy { UtilModule(this@IActivity) }
    private val httpClient: HttpClient by lazy { HttpClient(this@IActivity) }

    private val presenter: MainPresenter by inject{ parametersOf(utilModel, 
    httpClient) }

}

class MainPresenter(private val util: UtilModule, private val httpClient: HttpClient)

您的模块:

single { MainPresenter( it[0], it[1] ) }

答案 1 :(得分:0)

您可以将活动/片段实例动态附加到具有koin生命周期扩展的作用域实例注册表中。

val definition = BeanDefinition(
    scopeDefinition = this._scopeDefinition,
    primaryType = T::class,
    kind = Kind.Single,
    definition = { instance() }
)

val instanceMap = lifecycleScope._instanceRegistry.instances as HashMap<IndexKey, InstanceFactory<*>>
val factory = SingleInstanceFactory(this._koin, definition)
instanceMap[indexKey(T::class, null)] = factory

然后将其注入示波器定义中

scope<SomeActivity> {
    // inject activity with Scope.get()
    scoped { SomeModule(get()) }
}

最后,注入lifecycleScope:

val someModule: SomeModule by lifecycleScope.inject()

我写了一个演示来解释它是如何工作的: https://github.com/twiceyuan/KoinAndroidComponentInject