Dagger 2问题:没有@Provides方法就无法提供

时间:2017-01-07 20:09:13

标签: android dagger-2

我在我的项目中玩Dagger 2然后我遇到了这个错误编译。 - &GT; Error:(18, 21) error: ....MyManager cannot be provided without an @Provides-annotated method. ...MyManager is injected at ...SignInPresenter.<init>(myManager) ...SignInPresenter is provided at ...SignInComponent.signInPresenter()

我尝试研究这个主题,但我无法在我的代码中指出错误。我想我在某个地方犯了一个小错误,或者我在Dagger2中理解了一些错误。如果有人能指出错误。我真的很感激。

我的经理

public interface MyManager {
    Observable<User> getAllUsers();
}

SignIn Presenter

 @Inject
    public SignInPresenter(MyManager myManager) {
        this.myManager= myManager;
    }

我在 MySignInFragment

中做了类似的事情
   @Override protected void injectDependencies() {
        signInComponent = DaggerSignInComponent.builder()
                .myApplicationComponent(MyDaggerApplication.getMyComponents())
               .build();
    }

登录组件

@Component(modules = {MyModule.class},
        dependencies = {MyApplicationComponent.class})
public interface SignInComponent {
    SignInPresenter signInPresenter();
}

这是我的申请

public class MyDaggerApplication extends Application {
    private static MyApplicationComponent myApplicationComponent;


    @Override
    public void onCreate() {
        super.onCreate();
        myApplicationComponent = DaggerMyApplicationComponent.create();
        myApplicationComponent = DaggerMyApplicationComponent.builder().myModule(new MyModule(this)).build();
        myApplicationComponent.inject(this);
    }

    public MyApplicationComponent getMyAppComponents(){
        return myApplicationComponent;
    }

    public static MyApplicationComponent getMyComponents(){
        return myApplicationComponent;
    }
}

我的模块和组件类

@Component(modules = {MyModule.class})
public interface MyApplicationComponent {
    void inject(MyDaggerApplication myDaggerApplication);
}

@Module
public class MyModule {
    private final MyDaggerApplication myDaggerApplication;

    public MyModule(MyDaggerApplication myDaggerApplication){
        this.myDaggerApplication = myDaggerApplication;
    }

    @Provides
    @Singleton
    Context providesApplicationContext() {
        return this.myDaggerApplication;
    }

    @Provides
    @Singleton
    SharedPreferences providesSharedPreferences(Context context) {
        return context.getSharedPreferences("My_Pref", Context.MODE_PRIVATE);
    }

    @Provides
    @Singleton
    public MyDefaultManager providesMyDefaultManager(MyDefaultManager myDefaultManager,Context context){
        return myDefaultManager.getInstance(context);
    }
}

我猜我在DaggerApplication做错了。任何建议都将受到高度赞赏。 :)

1 个答案:

答案 0 :(得分:1)

假设MyDefaultManager实施MyManager,请将MyModule中的最终提供者更改为:

@Provides
@Singleton
public MyManager providesMyDefaultManager(MyDefaultManager myDefaultManager,Context context){
    return myDefaultManager.getInstance(context);
}

由于您希望专门返回? implements MyManager而不是MyDefaulManager的实例。