Dagger 2错误:“如果没有@Inject构造函数或@ Provide-annotated方法,则无法提供RepositoryImpl”

时间:2016-08-27 17:10:37

标签: android dagger-2

例如,我有以下界面:

public interface Repository {
    Observable<Pojo> getPojos();
}

及其实施:

public class RepositoryImpl implements Repository {

    public RepositoryImpl() { 

    }

    @Override
    public Observable<Pojo> getPojos() {
        return null;
    }   

}

模块:

@Module
class AppModule {

    public AppModule() {

    }

    @Provides
    @Singleton
    Repository provideRepositoryImpl() {
        return new RepositoryImpl();
    }

}

和组件:

@Singleton
@Component(modules = { AppModule.class })
public interface AppComponent {
    void inject(MainActivity mainActivity);   
}

当我尝试构建项目时,我会收到错误标题。我的代码中有什么问题?

2 个答案:

答案 0 :(得分:1)

仔细阅读你的错误(强调我的):

  

Dagger 2错误:如果没有@Inject构造函数或@ Provide-annotated方法,则无法提供“ RepositoryImpl

通常,这意味着您已尝试@Inject RepositoryImpl,而不是@Inject Repository。这一点尤为重要,因为您的Module直接调用RepositoryImpl构造函数,而不是让Dagger使用@Inject - 带注释的构造函数创建RepositoryImpl。 (如果有,您可以RepositoryImpl作为@Provides方法的参数或切换到@Binds方法,您可以在注入接口与实现之间做出选择。)

答案 1 :(得分:0)

我设置Dagger 2的方式是在我的项目中我添加了注入组件。像这样。

public class NyApplication extends Application {

InjectionComponent component;

@Override
public void onCreate() {
    super.onCreate();
    setDagger();
}

private void setDagger() {
    component = DaggerAppComponent.builder()
            .appComponent(new AppModule())
            .build();
    component.inject(this);
}

public InjectionComponent getComponent() {
    return component;
}}

然后在我的活动中无论它是什么。我像这样注入onCreate。

public class MainActivity extends Activity {

@Inject
Object object;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ((MyApplication) getApplication()).getComponent().inject(this);

}}

我希望这会对你有所帮助。

相关问题