实现多个接口的实体的 Dagger2 多模块注入

Dagger2 multimodule injection of entity that implements several interfaces

假设我们的应用程序中有以下模块(箭头表示取决于):

app -> {module1, module2} -> {核心模块}。

我们的module1定义了Interface1,我们的module2定义了Interface2。我们的应用程序模块定义了 Interface1n2Implementation(实现 Interface1 和 Interface2)并实例化为单例。

Q.: 在dagger2 生态系统方面,如何为module1 和module2 提供相同的Interface1n2Implementation 实例?

您的 AppModule 可以创建具有特定范围的实现(在本例中为 @Singleton),并且您可以有 2 个提供 return 这个实现实例的方法。

注意:未经测试

@Module
object AppModule {
    @Provides
    @Singleton
    internal fun provideImplementation() : Interface1n2Implementation = 
    Interface1n2Implementation()

    @Provides
    fun provideInterface1(implementation: Interface1n2Implementation) : Interface1 = implementation

    @Provides
    fun provideInterface2(implementation: Interface1n2Implementation) : Interface2 = implementation
}