【发布时间】:2019-04-03 22:43:19
【问题描述】:
注意这个问题可能和其他问题类似,但是它提供了一个更好的解释,附带代码,旨在找到问题的解决方案,其他问题提供的解决方案不适合。 p>
就在几天前,我开始开发一个 Android 模块化应用程序。我使用 Dagger 2 来处理依赖注入,我目前正面临一个奇怪的行为。 我有我的主应用程序模块和其他三个模块:
-
Core_Module:暴露了第三方库和存储层。 -
Localisation_Module:它公开了一个存储库以获取本地化信息。 -
Configuration_Module:它公开了一个存储库以获取配置参数。
Configuration_Module 和 Localisation_Module 都依赖于 Core_Module。
核心组件:
@Singleton
@Component(modules = [ApplicationModule::class, NetworkingModule::class, RepositoryModule::class])
interface CoreComponent {
@Named("retrofit")
fun retrofit(): Retrofit
@Named("retrofitWithCache")
fun retrofitWithCache(): Retrofit
fun storageRepository(): StorageRepository
}
本地化组件:
@Component(modules = [ServiceModule::class, RepositoryModule::class], dependencies = [CoreComponent::class])
@LocalisationScope
interface LocalisationComponent {
fun localisationService(): LocalisationService
fun localisationRepository(): LocalisationRepository
}
配置组件
@Component(modules = [ServiceModule::class, RepositoryModule::class], dependencies = [CoreComponent::class])
@ConfigurationScope
interface ConfigurationComponent {
fun configurationService(): ConfigurationService
fun configurationRepository(): ConfigurationRepository
}
应用组件
@Component(dependencies = [LocalisationComponent::class, ConfigurationComponent::class])
@ApplicationScope
abstract class ApplicationComponent {
abstract fun inject(mainActivity: MainActivity)
}
主应用程序
class MainApplication : Application() {
lateinit var applicationComponent: ApplicationComponent
override fun onCreate() {
super.onCreate()
this.registerDependencies()
}
private fun registerDependencies() {
val coreModule = CoreModule(applicationContext)
applicationComponent = DaggerApplicationComponent.builder()
.localisationComponent(LocalisationModule(coreModule).localisationComponent)
.configurationComponent(ConfigurationModule(coreModule).configurationComponent)
.build()
}
}
我决定设计这种架构是因为我想将功能分成独立的、可互换的模块,这样每个模块都包含执行特定功能并将单个模块导出到其他应用程序所需的一切。
不幸的是,我收到一条错误消息,指出不允许 Dagger 组件依赖于多个作用域组件。 有谁知道如何面对这种问题?
【问题讨论】:
-
'LocalisationComponent' 和 'ConfigurationComponent' 也应该是 '@Singleton'。
-
谢谢你们的回答。不幸的是,提出的解决方案不适合这种情况:(
标签: java android kotlin dependency-injection dagger-2