I've so far used Java's ServiceLoader to discover implementations of interfaces my app provides at runtime in the classpath, i.e. a classic plugin approach. I'm now starting to use Koin in the app (for Dependency Injection) and wondering whether I could actually use Koin to replace ServiceLoader
and implement plugin discovery with Koin (i.e. use Koin as Service Locator, which it actually seems to be rather than a DI framework).
What I'm struggling with is that in all the examples for Koin I saw so far, the implementations passed to single
/ singleOf
are static, i.e. known at compile time:
import dev.schuberth.stan.exporters.CsvExporter
import dev.schuberth.stan.exporters.ExcelExporter
// ...
interface Exporter
// ...
module {
// The "CsvExporter" and "ExcelExporter" implementations have to be
// known at compile time for this to work.
singleOf(::CsvExporter) bind Exporter::class
singleOf(::ExcelExporter) bind Exporter::class
}
// ...
val exporters = app.koin.getAll<Exporter>()
How would I implement discovery for an implementation of an interface that's contained in an external JAR that is only added to the app's classpath at runtime? In that case, I neither now the class's name nor the class's package at compile time (so even the @ComponentScan annotation would not work).
My hunch is that I'm supposed to create a Koin module
already in the plugin's code, not only in the app's code, and somehow use that via Koin from the app, but I have no idea how.