[英]How to pass an interface as parameter in koin
I'm so beginner in koin.我是 koin 的初学者。
I have a method that named "MesheRepoImpl" that get an interface as parameter.我有一个名为“MesheRepoImpl”的方法,它获取一个接口作为参数。
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.我知道我不能将接口传递给 Koin 中的方法,所以我创建了一个 class 并从接口扩展它,然后我在 koin 模块中添加了 class,所以我使用 class 作为 MesheRepoImpl 的参数。
But android studio gives me this error:但是 android 工作室给我这个错误:
Caused by: org.koin.core.error.NoBeanDefFoundException: |- No definition found for class:'com.app.meshe.data.repo.MesheRepo'.原因:org.koin.core.error.NoBeanDefFoundException:|- 未找到 class 的定义:'com.app.meshe.data.repo.MesheRepo'。 Check your definitions!
检查你的定义!
This is my Di module:这是我的 Di 模块:
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. 1 星线是我的 class 从接口延伸出来,2 星线是 class 获取接口作为参数。
How can I pass the interface as parameter, if I can't use a class?如果不能使用 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
.因此,只需实现
MeshoRepo
而不是将其作为参数传递给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:尝试直接回答您的问题,您可以在 Koin 模块中定义接口并传递它们,但您还必须提供它们的实现:
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.并且,请不要忘记接口不是 object。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.