【发布时间】:2021-01-25 20:43:48
【问题描述】:
我有 3 个存储库:
interface MainRepository {
...
}
interface LocalRepository {
...
}
interface WebRepository {
...
}
每个存储库都有自己的实现:
@Singleton
class MainRepositoryImpl @Inject constructor(
private val localRepository: LocalRepository,
private val webRepository: WebRepository
) : MainRepository {
...
}
@Singleton
class LocalRepositoryImpl @Inject constructor(
private val localMapper: LocalMapper
private val popularMovieDao: PopularMovieDao
) : LocalRepository {
...
}
@Singleton
class WebRepositoryImpl @Inject constructor(
private val webMapper: WebMapper,
private val popularMovieApi: PopularMovieApi
) : WebRepository {
...
}
如您所见,MainRepository 需要将其他两个存储库都注入其中,但是,我真的不知道该怎么做。
当然,我可以使用 LocalRepositoryImpl 或 WebRepositoryImpl 类型注入它,但我想使用 LocalRepository 或 WebRepository 类型注入它以获得更通用的方法。
这是我尝试编写的模块:
@InstallIn(ApplicationComponent::class)
@Module
object Module {
@Singleton
@Provides
fun provideWebRepository(): WebRepository {
return WebRepositoryImpl(mapper = WebMapper(), popularMovieApi = PopularMovieApi.getInstance())
}
@Singleton
@Provides
fun provideLocalRepository(): LocalRepository {
return LocalRepositoryImpl(mapper = LocalMapper(), // Here I can't really
// figure out how to get @Dao since it requires DB
// which requires context and etc
// which makes me think that I've got completely wrong approach to this)
}
}
我的 LocalData 模块:
@InstallIn(ApplicationComponent::class)
@Module
object LocalDataSourceModule {
@Singleton
@Provides
fun provideMainDatabase(@ApplicationContext context: Context): MainDatabase = MainDatabase.getInstance(context)
@Provides
fun providePopularMovieDao(mainDatabase: MainDatabase): PopularMovieDao = mainDatabase.popularMovieDao()
}
我的 WebData 模块:
@InstallIn(ApplicationComponent::class)
@Module
object RemoteDataSourceModule {
@Singleton
@Provides
fun providePopularMovieApi(): PopularMovieApi = PopularMovieApi.getInstance()
}
如何在维护接口类型(LocalRepository 和`WebRepository)的同时正确地注入我拥有的实现(LocalRepositoryImpl 和WebRepositoryImpl)??
【问题讨论】:
标签: android kotlin dependency-injection dagger-hilt