android - Koin 范围和接口(interface)

标签 android koin

我正在使用 Koin我项目中的 di 库。 lib 版本为 1.0.0-RC-1

我的模块:

val appModule = module {
    scope("UserScope") { UserToaster(androidContext()) as Toaster }
    scope("AnonScope") { AnonToaster(androidContext()) as Toaster }
}

我在我的 Application 类中开始 koin 并创建了 scope:

override fun onCreate() {
    super.onCreate()

    startKoin(this, listOf(appModule))
    getKoin().getOrCreateScope("AnonScope")
}

接下来,我尝试将 Toaster 的实现从当前作用域注入(inject) Activity 中的变量。这里的代码:

private val toaster: Toaster by inject(scope = "AnonScope")

之后我得到一个错误:

Caused by: org.koin.error.DependencyResolutionException: Multiple definitions found for type 'interface com.example.nkirilov.playground.Toaster (Kotlin reflection is not available)' - Koin can't choose between :
    Scope [name='UserScope',class='com.example.nkirilov.playground.Toaster']
    Scope [name='AnonScope',class='com.example.nkirilov.playground.Toaster']
    Check your modules definition, use inner modules visibility or definition names.

我不明白为什么这不起作用(如果使用具有不同名称的 single - 它会起作用)。那是 koin 错误吗?如何避免这个错误?

最佳答案

我是这样实现的

模块:

val navigationModule = module {
    scope(DI.APP_SCOPE) { ClassA().create }
    scope(DI.APP_SCOPE) { get(scopeId = DI.APP_SCOPE).classB }
    scope(DI.APP_SCOPE) { get(scopeId = DI.APP_SCOPE).classC }
}

val authModule = module {
    scope(DI.AUTH_SCOPE) { ClassA.create(ChildClassB(get(scopeId = DI.APP_SCOPE))) }
    scope(DI.AUTH_SCOPE) { get(scopeId = DI.AUTH_SCOPE).classB }
    scope(DI.AUTH_SCOPE) { get(scopeId = DI.AUTH_SCOPE).classC }
}

主要 Activity :

private val classC: ClassC by inject(scope = getKoin().getOrCreateScope(APP_SCOPE))

AuthActivity:

private val classC: ClassC by inject(scope = getKoin().getOrCreateScope(DI.AUTH_SCOPE))

关于android - Koin 范围和接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52221735/

相关文章:

android - 从 fragment 启动 IntentService

android - BeanInstanceCreationException : Can't create definition for Single

android - 依赖图在 Koin 或 Kodein 中如何工作?

android - 每次如何在koin中创建viewModel的新实例

安卓工作室 : How do I re-include an excluded library from auto-complete?

java - Android 为我的 Sqlite DB 中的每个字符串创建一个 TextView

android - 将拍摄的图像设置为墙纸的相机应用程序未获得所需的结果

android - 在 Jetpack Compose 中管理状态

dependency-injection - 面临将 sharedPreferences 和 sharedPrefrencesEditor 添加到 Koin 模块的问题

android - Koin依赖注入(inject)本地和远程数据源之间的切换