【发布时间】:2018-04-12 10:38:32
【问题描述】:
您好,我有两个模块在我的项目的域包中分开,并且有使用 DaggerAppComponent 手动注入自身的 firebase 实例服务类。
然后我有两个注入依赖项位于我提到的两个模块上。
ModuleOne 有一个叫做 storage 的依赖,ModuleTwo 有一个叫做 delegator。
当尝试将这两个注入到我的 firebase 服务类中时,它抱怨它无法从 ModuleTwo 找到委托注入器。
但是,如果我将委托者的提供方法接口复制到 ModuleOne 中,它有点工作(现在抱怨它的绑定多次但可以通过添加命名约定轻松解决该问题)。
这是一种 hacky 方式,我并不热衷于这样做,只是希望能够使用来自不同模块的任何依赖项。这可能吗?
下面是我的 firebase 服务类
class MyInstanceIdService : FirebaseInstanceIdService() {
@Inject
lateinit var delegator: AccountDelegatorContract
@Inject
lateinit var Storage: StorageContract
override fun onCreate() {
super.onCreate()
AndroidInjection.inject(this)
}
override fun onTokenRefresh() {
DaggerApplicationComponent.builder().application(application as MyApplication).build().inject(this)
val refreshToken = FirebaseInstanceId.getInstance().token
// val pianoStorage: PianoStorage = PianoStorage(this)
sendTokenToServer(refreshToken, storage.getUniqueId())
}
private fun sendTokenToServer(refreshToken: String?, uniqueId: String) {
//TODO: Send this new token to server
delegator.sendPushToken(PushTokenRequest(refreshToken!!, uniqueId))
}
这是 moduleOne,它代表主模块,其中包含在我的应用程序的多个域包中使用的依赖项。
@Module
abstract class MainModule {
@ContributesAndroidInjector(modules = [AccountModule::class])
@ViewScope
abstract fun bindInstanceIdService(): MyInstanceIdService
@Provides
@Singleton
@JvmStatic
fun provideApplicationContext(application: Application): Context = application
@Provides
@Singleton
@JvmStatic
fun provideStorageData(storage: MainStorage): StorageContract = storage
}
这是特定于域包的 ModuleTwo
@Module
abstract class AccountModule {
@Module
companion object {
@ViewScope
@JvmStatic
@Provides
fun providesAccountDelegator(accountDelegate: AccountDelegator): AccountDelegatorContract = accountDelegate
@ViewScope
@JvmStatic
@Provides
fun providesAccountControllerContract(accountNetworkController: AccountNetworkController): AccountControllerContract = accountNetworkController
}
}
我的应用程序组织在不同的包中,代表应用程序的一部分/域,例如帐户、用户、车辆、消息等,并且每个域都有自己的模块,该模块定义了与该域相关的特定依赖项。
我的问题是如何使用位于不同模块上的上述依赖项?
编辑:我的 appCOMponent 看起来像这样
@Singleton
@Component(modules = arrayOf(MainModule::class,
AccountModule ::class))
interface ApplicationComponent : AndroidInjector<DaggerApplication> {
fun inject(MyApplication: MyApplication)
fun inject(myInsanceIdService: MyInstanceIdService)
override fun inject(instance: DaggerApplication)
@Component.Builder
interface Builder {
@BindsInstance
fun application(applicaton: Application): Builder
fun build(): ApplicationComponent
}
}
【问题讨论】:
-
尝试添加 ContributesAndroidInjector 和 AndroidInjection.inject(this) 仍然没有乐趣
标签: android dependency-injection dagger-2 dagger