Reputation: 1920
I have an SocketHandler interface and two other classes that implement this interface. I want to implement this interface in several handlers and inject them by koin.
interface SocketHandler {
fun onReceive(socketResponses: Enums.SocketResponses, callback: (item: String) -> Unit)
}
class ClassAHandlerImpl : SocketHandler, KoinComponent {
override fun onReceive(
socketResponses: Enums.SocketResponses, callback: (item: String) -> Unit
) {
....
}
}
class ClassBHandlerImpl: SocketHandler, KoinComponent {
override fun onReceive(
socketResponses: Enums.SocketResponses, callback: (item: String) -> Unit
) {
....
}
}
And the Koin module implementation for those classes
val handlersModule = module {
single<SocketHandler> {
return@single ClassAHandlerImpl()
}
single<SocketHandler> {
return@single ClassBHandlerImpl()
}
...
}
However i get an exception
Caused by: org.koin.core.error.DefinitionOverrideException: Definition '[Single:'com.example.handlers.SocketHandler']' try to override existing definition. Please use override option or check for definition '[Single:'com.example.handlers.SocketHandler']'
Upvotes: 0
Views: 99
Reputation: 959
Koin doesn't know which SocketHandler
instance to retrieve since it's defined twice in the module.
You should use named parameters:
val handlersModule = module {
single<SocketHandler>(named("SocketHandlerA")) {
return@single ClassAHandlerImpl()
}
single<SocketHandler>(named("SocketHandlerB")) {
return@single ClassBHandlerImpl()
}
...
}
And then you can inject in your classes:
private val socketHandler by inject<SocketHandler>(named("SocketHandlerA"))
Upvotes: 1