android - 在 MVP Koin 中注入(inject) Activity 对象

标签 android dependency-injection kotlin mvp koin

我正在使用 Koin 将 Activity 注入(inject)演示者,但现有的 Activity 实例不会传递给演示者。相反,会创建新的。我错过了什么?

val mainModule = module {
    single<IStartupActivity> { StartupActivity() }
    factory<IStartupPresenter> { StartupPresenter(get()) }
}

class StartupPresenter(val view: IStartupActivity): IStartupPresenter {
}

class StartupActivity : Activity(), IStartupActivity {
    val presenter: IStartupPresenter by inject()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

I/KOIN: +-- 'inf.ecg.presenter.interfaces.IStartupPresenter' 
D/KOIN: |-- [Factory     [name='IStartupPresenter',class='inf.ecg.presenter.interfaces.IStartupPresenter']]
I/KOIN: |   +-- 'inf.ecg.view.interfaces.IStartupActivity' 
D/KOIN: |   |-- [Single [name='IStartupActivity',class='inf.ecg.view.interfaces.IStartupActivity']]
D/KOIN: |   |-- inf.ecg.view.implementations.StartupActivity@4176160
I/KOIN: |   \-- (*) Created
D/KOIN: |   !-- [inf.ecg.view.interfaces.IStartupActivity] resolved in 4.378594 ms
D/KOIN: |-- inf.ecg.presenter.implementations.StartupPresenter@ddfe619
I/KOIN: \-- (*) Created
D/KOIN: !-- [inf.ecg.presenter.interfaces.IStartupPresenter] resolved in 18.235835 ms

最佳答案

我知道这个问题不久前已经被问过,但这里是为那些最终来到这里的人提供的解决方案。

这可以通过将 Activity 声明为注入(inject)的参数来解决,如下所示:

val myModule = module {
    single<IStartupPresenter> { (view: IStartupActivity) ->  StartupPresenter(view) }
}

然后将其注入(inject)到您的 Activity 中:

class StartupActivity : Activity(), IStartupActivity {
    val presenter: IStartupPresenter by inject { parametersOf(this) }

...
}

关于injecting parameters的Koin文档.

关于android - 在 MVP Koin 中注入(inject) Activity 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52787061/

相关文章:

java - 在java中的单元测试的服务类中注入(inject)不断增长的依赖关系的最佳方法是什么

c# - EF 的 DbContext 的单例范围

java - 通过 JSON 配置选择策略

android - Kotlin:如何在 SharedPreferences 中保存数组列表

android - 为什么在将 gradle 项目添加到另一个 repo 后,IDE 中出现语法错误,即使在构建工作时也是如此?

android - 如何使用带有 WSL (bash) 的 Android Studio 作为你的 shell 终端?

java - 在 Oracle 本地主机中连接

c# - Ninject:绑定(bind)时定义命名约束

Android DialogFragment TextView setText() 不起作用

android - 使用 android studio 错误启动 Android 应用程序 : Fatal signal 13 SIGPIPE code -6