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

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

问题描述

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

我不清楚如何注入和访问上下文.我尝试按以下方式执行此操作:

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

然而,这会导致以下异常:

<块引用>

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

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

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

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

解决方案

未正确构建 Application 组件,需要传入 Application.这个 Dagger 2 示例完美地展示了如何做到这一点:https://github.com/google/dagger/tree/master/examples/android-simple/src/main/java/com/example/dagger/simple>

更新:
工作链接:https://github.com/yongjhih/dagger2-sample/tree/master/examples/android-simple/src/main/java/com/example/dagger/simple

I am using Dagger 2 and have it working however I now need access to the Android Application Context.

Its not clear to me how to inject and get access to the context. I have tried to do this as follows:

@Module
public class MainActivityModule {    
    private final Context context;
    
    MainActivityModule(Context context) {
        this.context = context;
    }

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

However this results in the following exception:

java.lang.RuntimeException: Unable to create application : java.lang.IllegalStateException: mainActivityModule must be set

If I inspect the Dagger generated code this exception is raised here:

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

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