Hi, could someone please share a complete example ...
# kodein
n
Hi, could someone please share a complete example how to use scopes? What I’m trying to do: I have a singleton which needs to be recreated when the server environment is changed from Test to Prod via the debug menu. I figured I should use scopes for that, but the documentation doesn’t have a complete working example that is easy to follow.
@salomonbrys maybe you can help?
s
I can work on a simple example.
n
cool thanks!
The singleton I have is passed a URL string to its constructor based on what is selected in the debug menu - prod vs test. It would be really helpful if your example relates to it 🙂
n
yes
This sample features a very simple
EnvironmentScope
that do not clear the memory when changing environment, and a more complex
OneEnvironmentScope
that do clear the memory when changing scope. Note that this sample is for JVM only. I could adapt it to KMP, if you need me to.
n
@salomonbrys Thanks a lot! I have one question though. In my case, the current environment comes from a singleton instance of a class called
DebugHelper
. which is also provided via Kodein. How should I get it for calling
registerContextFinder()
?
Copy code
val applicationModule: DI.Module = DI.Module("ApplicationModule") {
    // How to get debugHelper instance here?
    registerContextFinder<Environment> { debugHelper.env }
    bind() from scoped(OneEnvironmentScope).singleton {
       // instance setup here
    }
}
s
@nimrod, contextFinder cannot access DI right now. It should. Can you open a ticket in Kodein-DI github issues ?
In the meantime, this works (but makes my eyes bleed):
Copy code
lateinit var di: DI

di = DI {
    bind() from singleton { CurrentEnvironment(Environment.PROD) }

    // Choose one:
    //bind() from scoped(EnvironmentScope).singleton { API(context.baseUrl) }
    bind() from scoped(OneEnvironmentScope).singleton { API(context.baseUrl) }

    // This is needed to provide Kodein-DI the mean to find the current env.
    registerContextFinder<Environment> { di.direct.instance<CurrentEnvironment>().env }
}
n
@salomonbrys thanks once again! in my case I use
DI.Module("ApplicationModule") {
which doesn’t seem to have access to
direct
. Am I missing something?
s
Ouch... You're being too clean 😞 You'll have to wait for our next release, we'll try to be quick.
n
Hehe ok nevermind, thanks!