I use `fragmentFactory()` to inject Fragments into...
# koin-contributors
e
I use
fragmentFactory()
to inject Fragments into Activities and that works like a charm. I was wondering if I could use an
AppComponentFactory
to do the same for Activities and made a quick prototype:
Copy code
val componentFactoryModule = module {
    single<AppComponentFactory> { KoinComponentFactory() }
}

fun KoinApplication.componentFactory() {
    koin.loadModules(listOf(componentFactoryModule))
}

class KoinComponentFactory : AppComponentFactory(), KoinComponent {

    override fun instantiateActivity(
        cl: ClassLoader, className: String, intent: Intent?
    ): Activity {
        val clazz = Class.forName(className).kotlin
        val instance: Activity? = getKoin().getOrNull(clazz)
        return instance ?: super.instantiateActivity(cl, className, intent)
    }

}
add to startKoin:
Copy code
startKoin {
    componentFactory()
    ...
and register the factory in the manifest:
Copy code
tools:replace="android:appComponentFactory"
   android:appComponentFactory="mypackage.KoinComponentFactory"
This also works like a charm and I would love this to be part of the library itself but I'm not sure if this is the way to go and how this needs to be changed to play nicely with scopes?
a
Interesting idea. I would need to dive a bit more deeper to see limits of the API