Search code examples
androidkotlindependency-injectionkotlin-multiplatformkoin

Koin Android-KMM: I have nested scopes but injection is not working


I am getting this error. I am using Koin for dependency injection. I want my appointment repository to be alive as UserInfoContainer scope is alive. No definition found for class:'com.flow.domain.repository.AppointmentsRepository'. Check your definitions!

UserInfoContainer class

class UserInfoContainer(private val encryptedLocalDatabase: EncryptedLocalDatabase) :
    KoinScopeComponent {
    override val scope: Scope get() = getOrCreateScope().value
var user: User?
    get() = encryptedLocalDatabase.user
    set(it) {
        if (it != encryptedLocalDatabase.user) {
            encryptedLocalDatabase.user = it
            scope.close()
        }
        }
}

Koin file

single { UserInfoContainer(encryptedLocalDatabase = get()) }

    scope<UserInfoContainer> {
        scoped<AppointmentsRepository> {
            AppointmentsRepositoryImplementation(
                apiService = get(),
                clinicId = get<UserInfoContainer>().user.let { it!!.clinicId }
            )
        }
    }

AppointmentsUseCase class

class AppointmentsUseCase : KoinComponent {
    private val appointmentsRepository: AppointmentsRepository by inject()

    suspend fun getAppointments(startDate: LocalDateTime, endDate: LocalDateTime): List<Appointment> =
        appointmentsRepository.getAppointments(startDate, endDate)
}

Solution

  • That is how I should inject my dependencies in the UseCase

    class AppointmentsUseCase : KoinComponent {
        private val userInfoContainer: UserInfoContainer by inject()
        private val appointmentsRepository: AppointmentsRepository = userInfoContainer.scope.get()
    
        suspend fun getAppointments(
            startDate: LocalDateTime,
            endDate: LocalDateTime
        ): List<Appointment> =
            appointmentsRepository.getAppointments(startDate, endDate)
    }