Is there a way to tie a scope to an instance inste...
# koin
a
Is there a way to tie a scope to an instance instead of a string identifier (anonymous scope)? Let's assume I have a
Model
class, a
Controller
class and a
View
class. There can be several instances of
Model
in the application (scoped), but every one of these models has exactly one
Controller
(scoped). Furthermore it shall be possible to have multiple instances of
View
pointing to a pair of
Model
and
Controller
. Afaik you can only tie a scope to a scope-id (string)
koin.createScope<Model>(scopeId = "I have to provide an id")
.
koin.createScope<Model>()
works, but only once since it is creating a scope-id from the class name. I want a scope to be bound to an instance. Is that somehow possible? I would love to see an API like this:
Copy code
val scope1 = koin.createScope<Model>() // idea: scope should be tied to an instance of 'Model' instead of scopeId
val model1 = scope1.get<Model>() // scoped
val controller1 = scope1.get<Controller>() // scoped
val view11 = scope.get<View>() // factory
val view12 = scope.get<View>()

val scope2 = koin.createScope<Model>() // should create another scope tied to another instance of 'Model'
val model2 = scope1.get<Model>() // scoped
val controller2 = scope1.get<Controller>() // scoped
val view21 = scope.get<View>() // factory
val view22 = scope.get<View>()
a
this should be the case in 2.1.x
a
Thank you very much (especially for the link to the docs)!
okay, I still don't get it. Here a very simple example:
Copy code
class A
class B(val a: A)

val module = module {
    factory { A() }
    scope<A> {
        scoped { B(get()) }
    }
}

fun main() {
    val koin = startKoin { modules(module) }.koin

    val a: A = koin.get()
    val b: B = a.scope.get()

    println(a === b.a) // false, but true expected
}
How does B get A within its own scope?
@arnaud.giuliani see question above
a
not directly
you can try parameter injection
Copy code
val b: B = a.scope.get { parametersOf(a) }
but ... really handy 😕
a
@arnaud.giuliani Is there some method to handle it from the module side, so I can use the API just like described above:
Copy code
val a: A = koin.get()
val b: B = a.scope.get()
Is it worth to create an issue for that or am I the only one who would use such construct?
a
its a new feature, as the idea is to pass the source object of the Scope in the scope itself
when you have a scoped definition like
scoped { YourClass() }
we are already using the current scope
we just need to pass the source object
please open a new feature issue regarding this