【问题标题】:How to provide Context with Hilt Android?如何为 Hilt Android 提供上下文?
【发布时间】:2021-02-16 13:37:38
【问题描述】:

我正在尝试将项目迁移到 Hilt,但遇到以下问题,不确定如何使用 Hilt 传递上下文。如果我删除 provideContext 方法,那么它会抱怨以下错误:

error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ApplicationContext android.content.Context cannot be provided without an @Provides-annotated method.

但我的理解是,在 Hilt 中我们不需要 provideContext 方法,我们可以像下面这样使用 @ApplicationContext

@Inject
public CardLayoutManager(@ApplicationContext Context context) {
    mContext = context;
}

我错过了什么吗?

【问题讨论】:

  • AFAIK 您不能直接使用该注释注入上下文。这是为模块保留的。
  • 请查看developer.android.com/training/dependency-injection/…的示例 public class AnalyticsServiceImpl implements AnalyticsService { private final Context context; @Inject AnalyticsAdapter(@ApplicationContext 上下文上下文) { this.context = context;那么我们还需要一个provideContext方法吗?
  • 您是否创建了一个模块来为 CardLayoutManager 提供范围(即 SingletonScope)?如果是,请分享代码
  • @AndroidDev 你找到解决方案了吗?这让我发疯了

标签: android kotlin dependency-injection dagger dagger-hilt


【解决方案1】:

你需要正确地注解构造函数:

class CardLayoutManager @Inject constructor(@ApplicationContext val context: Context) {
}

【讨论】:

  • 那是一个 Java 类。即使在 Kotlin 文件中,构造函数注入也会出现同样的错误。
  • 据我所知,无论您在何处使用 Hilt 组件,都需要使用 @AndroidEntryPoint 注释您的入口类,以便加载依赖关系图。这是你的情况吗?
  • 确保您记得包含val 关键字!我忘了包括它,一旦我像你的回答一样添加它,我的问题就解决了。
【解决方案2】:

移除@ApplicationContext注解

我已阅读所有文档超过 5 次,尝试了正确的方法并更新了所有 Hilt 库,但问题仍然存在。

一旦我删除了注释,它就可以完美运行,这很奇怪,因为我在其他项目中使用了正确的方法(使用 @ApplicationContext 注释)。

【讨论】:

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