Dagger 2注入Android应用程序上下文 [英] Dagger 2 injecting Android Application Context
问题描述
我正在使用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屋!