Search code examples
androiddagger-2daggermulti-module

Dagger2 multimodule injection of entity that implements several interfaces


Let's say we have the following modules in our application (arrow means depends on) :

app -> {module1, module2} -> {core module}.

Our module1 has Interface1 defined, and our module2 has Interface2 defined. Our app module has Interface1n2Implementation (implements Interface1 and Interface2) defined and instantiated as singleton.

Q.: In terms of dagger2 ecosystem, how to provide module1 and module2 with same instance of Interface1n2Implementation?


Solution

  • Your AppModule can create the implementation with a specific Scope (@Singleton in this case) and you can have 2 provides methods which return this implementation instance.

    NOTE: Untested

    @Module
    object AppModule {
        @Provides
        @Singleton
        internal fun provideImplementation() : Interface1n2Implementation = 
        Interface1n2Implementation()
    
        @Provides
        fun provideInterface1(implementation: Interface1n2Implementation) : Interface1 = implementation
    
        @Provides
        fun provideInterface2(implementation: Interface1n2Implementation) : Interface2 = implementation
    }