Dagger 2注入Android应用程序上下文 [英] Dagger 2 injecting Android Application Context

查看:154
本文介绍了Dagger 2注入Android应用程序上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Dagger 2,并且可以使用它,但是现在我需要访问 Android应用程序上下文.

我不清楚如何注入和访问上下文.我尝试这样做,如下所示:

  @Module公共类MainActivityModule {私有最终上下文上下文;MainActivityModule(Context context){this.context =上下文;}@提供@Singleton上下文provideContext(){返回上下文;} 

但这会导致以下异常:

java.lang.RuntimeException:无法创建应用程序:java.lang.IllegalStateException:必须设置mainActivityModule

如果我检查Dagger生成的代码,则会在此处引发此异常:

  public Graph build(){如果(mainActivityModule == null){抛出新的IllegalStateException(必须设置mainActivityModule");}返回新的DaggerGraph(this);} 

我不确定这是否是注入Context的正确方法-我们将不胜感激任何帮助.

解决方案

未正确构建应用程序组件,需要传入应用程序.这个Dagger 2示例完美展示了如何执行此操作: https://github.com/google/dagger/tree/master/examples/android-simple/src/main/java/com/example/dagger/simple

更新:
工作链接: 解决方案

Was not correctly building the Application component, needed to pass in the Application. This Dagger 2 example perfectly shows how to do this: https://github.com/google/dagger/tree/master/examples/android-simple/src/main/java/com/example/dagger/simple

Update:
Working link: https://github.com/yongjhih/dagger2-sample/tree/master/examples/android-simple/src/main/java/com/example/dagger/simple

这篇关于Dagger 2注入Android应用程序上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆