【问题标题】:Migrating to Hilt from Dagger2从 Dagger2 迁移到 Hilt
【发布时间】:2021-05-23 19:41:38
【问题描述】:

我正在尝试在此处遵循 Hilt 迁移指南: https://dagger.dev/hilt/migration-guide.html

并用以下注释注释了我的所有模块:

@InstallIn(SingletonComponent::class)

但是,我的服务、片段和活动的“贡献者”模块遇到了问题。

每个模块都有一个,

@Module
@InstallIn(SingletonComponent::class)
abstract class FragmentContributorModule {
    @ContributesAndroidInjector
    internal abstract fun contributeMyFragment(): MyFragment
}

@Module
@InstallIn(SingletonComponent::class)
abstract class ActivityContributorModule {
    @ContributesAndroidInjector
    internal abstract fun contributeMyActivity(): MyActivity
}


@Module
@InstallIn(SingletonComponent::class)
abstract class ServiceContributorModule {
    @ContributesAndroidInjector
    internal abstract fun contributeMyService(): MyService
}

在编译期间,每个“贡献”函数都会出错:

  com.test.ActivityContributorModule_ContributeMyActivity$defaultsDebug is missing an @InstallIn annotation. If this was intentional, see https://dagger.dev/hilt/compiler-options#disable-install-in-check for how to disable this check.

我还尝试对每个模块使用 ServiceComponent::class、FragmentComponent::class 和 ActivityComponent::class,但没有成功。我正在尝试分段迁移项目,因此我认为在所有内容都升级到 Hilt 之前我无法删除这些项目。

有什么想法吗?

【问题讨论】:

  • 曾经尝试将它们放入单独的文件中吗?
  • 上面的每个模块都在一个单独的文件中。

标签: android dagger-2 dagger-hilt


【解决方案1】:

答案就在这里:

警告:未使用 @InstallIn 注释的模块不会被使用 通过希尔特。 Hilt 默认情况下会在未注释的模块出现时引发错误 已找到,但可以禁用此错误。

起初我并没有 100% 清楚,但我为服务/片段/活动提供的贡献者模块仅用于 Dagger,而不是 Hilt。因此,如果您尝试分段迁移项目,您可以保留这些模块,直到您开始为您的服务/片段/活动提供 Hilt 入口点。但是,如果您这样做,则需要告诉 Hilt 忽略它因缺少 @InstallIn 而引发的错误。

有关如何在此处禁用它的更多信息:

https://dagger.dev/hilt/compiler-options.html#disable-install-in-check

默认情况下,Hilt 检查@Module 类中的@InstallIn 注解 并在丢失时引发错误。这是因为如果有人 不小心忘记将@InstallIn 放在模块上,这可能是非常 很难调试 Hilt 没有捡起它。

不过,此检查有时可能过于宽泛,尤其是在 迁移的中间。要关闭此检查,可以使用此标志:

-Adagger.hilt.disableModulesHaveInstallInCheck=true。

或者,可以在单个模块中禁用检查 通过使用 @DisableInstallInCheck 注释模块来达到级别。

【讨论】:

    猜你喜欢
    • 2022-11-04
    • 1970-01-01
    • 2022-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多