Dagger 2 - 无法初始化

Dagger 2 - Can't initialize

当我编译我的 Android 项目时,我发现了这样的错误:

Error:(15, 13) 错误:如果没有 @Provides-annotated 方法,则无法提供 android.content.Context。 android.content.Context在com提供......di.components.AppComponent.getContext()

我的组件:

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    Context getContext();
    DataManager getDataManager();
}

我的模块:

@Module
public class AppModule {
    protected final Application mApplication;

    public AppModule(Application application) {
        mApplication = application;
    }

    @Provides
    @Singleton
    Application provideApplication() {
        return mApplication;
    }

    @Provides
    @ApplicationContext
    @Singleton
    Context provideContext() {
        return mApplication;
    }

    @Provides
    @Singleton
    DataManager provideDataManager() {
        return new DataManager();
    }
}

您的组件说它可以提供 Context:

@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  Context getContext();
}

当它只知道 @ApplicationContext Context(注意限定符?)时:

@Module
class AppModule {

  @Provides
  @Singleton
  @ApplicationContext
  Context provideContext() {
    return mApplication;
  }
}

您可以删除 @ApplicationContext 限定符并仅从您的模块中提供 Context,如果您还尝试提供您的活动上下文,这可能会妨碍您,或者您保留您的限定符并实际提供 qualified context:

@Singleton
@Component(modules = {AppModule.class})
interface AppComponent {
  @ApplicationContext
  Context getContext();
}

如果您尝试使用/注入应用程序上下文,您还需要使用限定符:

@ApplicationContext @Inject Context mContext;