Dagger 2 injecting Android Application Context

user3521637 picture user3521637 · Jun 7, 2015 · Viewed 40.6k times · Source

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.

Answer

EpicPandaForce picture EpicPandaForce · Nov 16, 2015
@Module
public class MainActivityModule {    
    private final Context context;

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

    @Provides //scope is not necessary for parameters stored within the module
    public Context context() {
        return context;
    }
}

@Component(modules={MainActivityModule.class})
@Singleton
public interface MainActivityComponent {
    Context context();

    void inject(MainActivity mainActivity);
}

And then

MainActivityComponent mainActivityComponent = DaggerMainActivityComponent.builder()
    .mainActivityModule(new MainActivityModule(MainActivity.this))
    .build();