Hello, I'm trying to set up my multiplatform proje...
# kodein
s
Hello, I'm trying to set up my multiplatform project with Kodein DI, and I'm wondering if there is a recommended way to create a
DI
to provide platform-specific implementations. Basically, I have an
interface
in my common code that I have created a platform specific implementation for in JVM (no other platforms yet, since common/jvm is enough for my current level of multiplatform exploration). I originally decided to inject the platform specific code into the constructor without a framework:
class SomeClass(val commonInterfaceName: CommonInterfaceName)
and then inject the implementation when I start the app from the JVM entry point. I can do the same thing now by injecting a
DI
instead, but I want to be able to create a
DI
module that I know contains all of these bindings. I'm wondering if there is a standard way to ensure that the
DI
being passed in has all of the necessary bindings (which I guess gets into a broader question of compile-time verification). Or if there is a way to I'm not sure if what I'm saying is clear or not. Also, before you ask why I'm not using
expect/actual
, the answer is because I don't know if/when I should. It seemed like interfaces would be more robust and provide for dependency injection (in the way that I was doing it, at least). I'm still trying to work out what multiplatform best practices look like.
j
Well you should create the application component/module in each application. Then you can bind in each of those the platform specific implementation to the common interface
for example:
Copy code
// In my JS component:
fun main() {
    val di = DI {
        import(applicationModule()) // Common application module
        bind<LocalStorage>() with singleton { DefaultLocalStorage(instance()) } // Binding the DefaultLocalStorage, which is platform specific, to the LocalStorage interface
    }
}
Copy code
// Android:
Copy code
class Application: Application(), DIAware {

    override val di by DI.lazy {
        import(applicationModule()) // Same common application module
        bind<Context>() with instance(this@Application)
        bind<LocalStorage>() with singleton { DefaultLocalStorage(instance(), instance()) } // Binding the LocalStorage to the DefaultLocalStorage from the Android component
    }
}