Dagger 2注入Android上下文 [英] Dagger 2 injecting Android Context

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

问题描述

我正在使用Dagger 2并使其正常工作,但是现在我需要访问Android应用程序上下文.

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

@Module
public class MainActivityModule {    
    private final Context context;

    MainActivityModule(Context context) {
        this.context = context;
    }

@Provides @Singleton
Context provideContext() {
    return context;
}

但这会导致以下异常:

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

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

public Graph build() {  
    if (mainActivityModule == null) {
        throw new IllegalStateException("mainActivityModule must be set");
    }
    return new DaggerGraph(this);
}

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

解决方案

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

更新:
工作链接:

I am not sure if this is the correct way to get Context injected - any help will be greatly appreciated.

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天全站免登陆