Dagger 2.22 - Unable to provide app context to module

Viewed 71

I'm new to dagger and am having a hard time understanding how to pass the app context to a module and then to other classes. I have experience with Guice but not Dagger. I know that there have already been a lot of posts on this yet I'm unable to figure out what I need to do to get it running.

My code below:

Component:

@Component(
    modules = {
      AndroidSupportInjectionModule.class,
      ActivityBuildersModule.class,
      AppModule.class
    })
public interface AppComponent extends AndroidInjector<ManatimeApplication> {

  @Component.Builder
  interface Builder {
    @BindsInstance
    Builder application(Application application);

    AppComponent build();
  }
}

Application:

public class ManatimeApplication extends DaggerApplication {

  @Override
  protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
    Log.d("DAGGER", "ManatimeApplication hash: " + hashCode());
    return DaggerAppComponent.builder().application(this).build();
  }
}

Modules:

ActivityBuildersModule:

@Module
public abstract class ActivityBuildersModule {

    @ContributesAndroidInjector
    abstract MainActivity contributeMainActivity();
}

AppModule:

public class AppModule {

    private Application context;

    public AppModule(Application context) {
        this.context = context;
    }

    @Provides
    static String test()    {
        return "dagger test";
    }

    @Provides
    Context provideAppContext() {
        Log.d("DAGGER", "ManatimeApplication in AppModule hash: " + context.hashCode());
        return context;
    }
}

Compilation of this code fails with the message:

> Task :app:compileDebugJavaWithJavac FAILED
/Users/sunnykumar/AndroidStudioProjects/MyApplication/app/src/main/java/com/manatime/ManatimeApplication.java:6: error: cannot find symbol
import com.manatime.di.DaggerAppComponent;
                      ^
  symbol:   class DaggerAppComponent
  location: package com.manatime.di
/Users/sunnykumar/AndroidStudioProjects/MyApplication/app/src/main/java/com/manatime/di/AppComponent.java:22: error: @Component.Builder is missing setters for required modules or components: [com.manatime.di.AppModule]
  interface Builder {
  ^
2 errors

Questions:
1) Will I have to create the AppModule with getApplicationContext() in ManatimeApplication and set it in the builder?
2) Is there another way to solve this?
3) What does @BindsInstance do if it does not bind the value of the application I set in the builder?
4) Do the values set in the Component Builder trickle to the app module?

0 Answers
Related