简体   繁体   中英

How to pass an interface as parameter in koin

I'm so beginner in koin.

I have a method that named "MesheRepoImpl" that get an interface as parameter.

I know that I can't pass an interface to a method in Koin, so I created a class and extends that from the interface then I added that class in koin module, so I use the class as parameter for MesheRepoImpl.

But android studio gives me this error:

Caused by: org.koin.core.error.NoBeanDefFoundException: |- No definition found for class:'com.app.meshe.data.repo.MesheRepo'. Check your definitions!

This is my Di module:

val mesheModule =
    module {
        single { getInstance(androidContext()) }
        single { MesheLocalDataSource() } //*
        single { MesheRepoImpl(get()) } //**
        factory { TaskViewModelFactory(get()) }
        viewModel { TaskViewModel(get()) }
        viewModel { RewardViewModel(get()) }
        viewModel {MainViewModel()}
    }

The 1 star line is my class that extends from the interface and the 2 stars line is the class that get interface as parameter.

How can I pass the interface as parameter, if I can't use a class?

Since there's still no answer, I'd advise you to consider going with

interface MesheRepo
class MeshoRepoImpl(): MeshoRepo

over your

interface MesheRepo
class MeshoRepoImpl(val IRepo: MeshoRepo)

So, just implement MeshoRepo over passing it as an argument to MeshoRepoImpl .

Trying to answer directly your question, you are able to define interfaces in Koin module and pass them, but you have to provide their implementations, as well:

val mesheModule = module {
  single<MeshoRepo> { MeshoRepoImpl() }
  single { MeshoRepoImpl(get()) } // <-- it's like a deadlock, so I still do not see any sense to pass an interface over implementing it
}

And, please, do not forget that an interface is not an object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM