docs/reference/koin-core/context-isolation.md
Context isolation allows SDK makers to use Koin without conflicting with the host application's Koin instance.
:::info For general Koin setup, see Starting Koin. :::
Instead of using startKoin (which registers in GlobalContext), use koinApplication:
// Isolated Koin context for your SDK
object MySdkKoinContext {
private val koinApp = koinApplication {
modules(sdkModule)
}
val koin = koinApp.koin
}
val sdkModule = module {
single<SdkService>()
single<SdkRepository>()
}
Create a custom KoinComponent that uses your isolated context:
internal interface SdkKoinComponent : KoinComponent {
// Override to use isolated context
override fun getKoin(): Koin = MySdkKoinContext.koin
}
// Usage in your SDK classes
class MySdkClass : SdkKoinComponent {
private val service: SdkService by inject() // Uses isolated context
}
Override getKoin() in tests to use the isolated context:
class SdkTest : KoinTest {
override fun getKoin(): Koin = MySdkKoinContext.koin
@Before
fun setUp() {
val testModule = module {
single<SdkService> { MockSdkService() }
}
koin.loadModules(listOf(testModule))
}
@After
fun tearDown() {
koin.unloadModules(listOf(testModule))
}
}