Hi, I have a scope in which multiple classes rely ...
# koin
s
Hi, I have a scope in which multiple classes rely on a unique mapId in this scope. I’m trying to find a nice way of injecting it throughout the scope. I can define my mapIdProvider in my scope as follow :
scoped { (mapId: String) -> MapIdProvider(mapId = mapId) }
but I need to call
myScope.get { parametersOf(getMapId()) }
directly after the scope creation so that the mapId is passed to the bean definition. It seems that
Scope
class can also have some parameters so I tried
Copy code
koin.createScope<RootActivityScopeKey>().also {
    it.addParameters(parametersOf(getMapId()))
}
but then I get
Can't get injected parameter #0 from DefinitionParameters[] for type 'java.lang.String'
I tried removing the definition in the scope adding the
Copy code
koin.createScope<RootActivityScopeKey>().also {
    it.addParameters(parametersOf(MapIdProvider(getMapId())))
}
but no success either. Is there a better way to inject that
MapIdProvider
? note that
MapIdProvider
is just a dataClass that holds the mapId
t
You could use
createScope(id, source)
and provide the
mapId
as source there. Then it should be possible to crate the MapIdProvider as
scoped { MapIdProvider(mapId = getSource()) }
s
I’ll try that
Copy code
@Suppress("UNCHECKED_CAST")
private fun <T : Any> resolveInstance(
        qualifier: Qualifier?,
        clazz: KClass<T>,
        parameters: ParametersDefinition?
): T {
    if (_closed) {
        throw ClosedScopeException("Scope '$id' is closed")
    }
    val indexKey = indexKey(clazz, qualifier)
    return _instanceRegistry.resolveInstance(indexKey, parameters)
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope")
                getFromSource(clazz)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in current scope's source")
                _parameters?.getOrNull<T>(clazz)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in injected parameters")
                findInOtherScope<T>(clazz, qualifier, parameters)
            }
            ?: run {
                _koin._logger.debug("'${clazz.getFullName()}' - q:'$qualifier' not found in linked scopes")
                throwDefinitionNotFound(qualifier, clazz)
            }
}
reading the code I don’t understand why it would be better from source or from _parameters
t
I think
source
is cleaner and a bit more generic.
s
Thanks @tynn, I’m not sure why the parameter parts doesn’t work but the source one works like a charm