Koin 单例注入带有私有参数的构造函数

Koin singleton inject constructor with private parameter

你好我刚学Koin,这个Dagger2class在Koin 2.0中是怎么提供的?

@Singleton
open class AppExecutors(private val diskIO: Executor, private val networkIO: Executor, private val mainThread: Executor) {

    @Inject
    constructor() : this(
            Executors.newSingleThreadExecutor(),
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1),
            MainThreadExecutor())

    fun diskIO(): Executor {
        return diskIO
    }

    fun networkIO(): Executor {
        return networkIO
    }

    fun mainThread(): Executor {
        return mainThread
    }

    private class MainThreadExecutor : Executor {
        private val mainThreadHandler = Handler(Looper.getMainLooper())
        override fun execute(command: Runnable) {
            mainThreadHandler.post(command)
        }
    }
}

我试过这个:

single<AppExecutors> { AppExecutors(
    Executors.newSingleThreadExecutor(),
    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1),
    AppExecutors.MainThreadExecutor())
}

但是 AppExecutors.MainThreadExecutor() 是私人的。是唯一的解决方案吗public?

好吧,使用 DI 从外部注入一些私有实现细节的想法有点奇怪。

另外,Dagger2 中的解决方案是一个实际围绕依赖注入工作的技巧。

因此您需要做出决定:我是否希望它成为私有实现细节?如果是,我会建议使用默认参数值并仅在需要重写此实现时才使用注入,例如用于检测。

open class AppExecutors(
    private val diskIO: Executor, 
    private val networkIO: Executor, 
    private val mainThread: Executor = AppExecutors.MainThreadExecutor()) {

并且:

single<AppExecutors> { AppExecutors(
    Executors.newSingleThreadExecutor(),
    Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() + 1)))
}

(请记住,在 Kotlin 中使用默认参数值最终与在原始示例中使用多个构造函数相同。)

否则你应该制作它 public 并从 class 中提取它。