Search code examples
androidkotlinkodein

How to access an instance from one Kodein module in a different module?


When using Kodein, if I have 2 modules and module B needs to use an instance from module A, is the best practice to import module A into module B or is there a better way to do it?

For example, I have a networkingModule:

val networkingModule = Kodein.Module("networking") {
    bind<Retrofit>() with singleton {
        Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .build()
    }
}

And subscribersModule needs the Retrofit instance from networkingModule:

val subscribersModule = Kodein.Module("subscribersModule") {
    import(networkingModule)
    bind<SubscribersService>() with singleton {
        instance<Retrofit>().create(SubscribersService::class.java)
    }
}

Is adding the import(networkingModule) in subscribersModule the best way to do it?


Solution

  • At the end, if your modules are used in one project, you're not force to make them dependant.

    Instead you can import them in a global container, like this:

    val applicationContainer = Kodein {
        import(subscribersModule)
        import(networkingModule)
        // ...
    }
    

    Kodein-DI will solve the dependencies for you.