多模块项目:如何设置 Dagger 来提供接口但隐藏特定于实现的依赖项?

gpu*_*nto 5 android modularization dagger dagger-2 android-module

在我的应用程序中,我有两个模块:apprepository
repository依赖于 Room,并且有一个GoalRepository接口:

interface GoalRepository
Run Code Online (Sandbox Code Playgroud)

和一个GoalRepositoryImpl内部类,因为我不想将它或 Room 依赖项暴露给其他模块

@Singleton
internal class GoalRepositoryImpl @Inject constructor(private val dao: GoalDao) : GoalRepository
Run Code Online (Sandbox Code Playgroud)

app取决于repository获取一个GoalRepository实例。目前,
我有一个:GoalRepositoryModule

@Module
class GoalRepositoryModule {
    @Provides
    @Singleton
    fun provideRepository(impl: GoalRepositoryImpl): GoalRepository = impl

    @Provides
    @Singleton
    internal fun provideGoalDao(appDatabase: AppDatabase): GoalDao = appDatabase.goalDao()

    @Provides
    @Singleton
    internal fun provideDatabase(context: Context): AppDatabase =
        Room.databaseBuilder(context, AppDatabase::class.java, "inprogress-db").build()
}
Run Code Online (Sandbox Code Playgroud)

问题是这不会编译(显然),因为公共provideRepository函数正在公开GoalRepositoryImpl,即一个internal类。
如何构建我的 Dagger 设置来实现我想要的?


编辑:
我尝试provideRepository按照 @David Medenjak 评论进行内部处理,现在 Kotlin 编译器抱怨它无法解析 RoomDatabase 依赖项:

Supertypes of the following classes cannot be resolved. Please make sure you have the required dependencies in the classpath:
    class xxx.repository.database.AppDatabase, unresolved supertypes: androidx.room.RoomDatabase    
Run Code Online (Sandbox Code Playgroud)

为了完整起见,模块内我的组件的代码app

@Component(modules = [ContextModule::class, GoalRepositoryModule::class])
@Singleton
interface SingletonComponent
Run Code Online (Sandbox Code Playgroud)

gpu*_*nto 1

查看 Dagger 生成的代码后,我了解到错误在于使模块@Component内部app依赖于模块@Module内部repository。所以我在模块内部
单独做了一个,并使模块的依赖于它。 @Componentrepositoryapp

代码

repository模块的组成部分:

@Component(modules = [GoalRepositoryModule::class])
interface RepositoryComponent {
    fun goalRepository(): GoalRepository
}
Run Code Online (Sandbox Code Playgroud)

app一个:

@Component(modules = [ContextModule::class], dependencies = [RepositoryComponent::class])
@Singleton
interface SingletonComponent
Run Code Online (Sandbox Code Playgroud)

这样,RepositoryComponent负责构建Repository并了解其所有依赖项,而只SingletonComponent需要了解RepositoryComponent.