Dagger 2 俯视提供方法

Dagger 2 is overlooking provides method

在我的 Android 应用程序中,我试图将 DatabaseHelper 对象注入到 ArticleView 中,但 Dagger 抱怨并显示以下错误消息:

Error:(11, 7) error: android.content.Context cannot be provided without an @Provides-annotated method.
dk.jener.paperflip.ArticleActivity.database
[injected field of type: dk.jener.paperflip.model.retriever.DatabaseHelper database]
dk.jener.paperflip.model.retriever.DatabaseHelper.<init>(android.content.Context context)
[parameter: android.content.Context context]

我该如何解决?

我的代码如下:

@Singleton
@Module
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    @Inject
    public DatabaseHelper(Context context) {
        super(context, "foobar", null, 1);
    }
    ...
}

@Module
public class ApplicationContextModule {
    private final Context context;

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

    @Provides
    @Singleton
    public Context provideApplicationContext() {
        return context;
    }
}

@Singleton
@Component(modules = { DatabaseHelper.class })
public interface RetrieverComponent {
    void inject(ArticleActivity activity);
}

public class ArticleActivity extends AppCompatActivity {
    @Inject
    DatabaseHelper database;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        RetrieverComponent component = DaggerRetrieverComponent.builder()
                .applicationContextModule(new ApplicationContextModule(getApplicationContext()))
                .build();
        component.inject(this);
    }
    ...
}

据我所知,Context 已经由 ApplicationContextModule#provideApplicationContext 提供。

在提供的代码中,您似乎错过了在组件中包含 ApplicationContextModule 模块。它应该是这样的:

@Component(modules = { ApplicationContextModule.class })

另外 DatabaseHelper 不需要有 @Module 注释(它不是一个模块,只是一个普通的 class)。