如何使用Koin DI将应用程序上下文从“应用程序"模块注入到“网络"模块 [英] How to Inject application context from 'app' module to 'network' module using Koin DI

查看:260
本文介绍了如何使用Koin DI将应用程序上下文从“应用程序"模块注入到“网络"模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于Koin DI(版本1.0.1)开发一个带有2个模块(:app和:network)的应用程序.我在:network模块中具有上下文"的要求.下面是我的实现方式:

I'm developing an application based on Koin DI (ver : 1.0.1) with 2 modules(:app and :network). I have a requirement in :network module to have "Context". Below is how I implemented:

**Module**:
val appModule = module {
    viewModel { LoginViewModel(get()) }
}

**Activity**:
private val viewModel by viewModel<LoginViewModel>()

**ViewModel**:
class LoginViewModel(val context: Context): ViewModel() {
  ...
  // Send "context" to network class in :network module
  ...
 }

问题:有什么方法可以将上下文直接发送到:network模块中的网络类?

Question: Is there any way we can directly send context to network class in :network module?

推荐答案

@Rajat和@Andrey的答案都是正确的.实际上,如果您查看

Both answers by @Rajat and @Andrey are correct. In fact if you look at the sources, you will see that androidContext() is just an extension function to get(), so these 2 definitions are identical:

val appModule = module {
    viewModel { LoginViewModel(get()) }
}

...

val appModule = module {
    viewModel { LoginViewModel(androidContext()) }
}

回答您的问题,因为get()androidContext()module DSL对象的成员,您可以这样做:

Answering your question, since get() and androidContext() are members of the module DSL object, you could do this:

val networkModule = module {
   single { Network(androidContext()) }
}

或者简单地说(为简洁起见,我更喜欢这个):

Or simply (I prefer this one for brevity):

val networkModule = module {
   single { Network(get()) }
}

这篇关于如何使用Koin DI将应用程序上下文从“应用程序"模块注入到“网络"模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆