Android Dagger不能在我的活动中插入演示者
我正在使用Dagger 1将Android应用程序重构为MVP架构 我的代码大致如下所示:Android Dagger不能在我的活动中插入演示者,android,dagger,Android,Dagger,我正在使用Dagger 1将Android应用程序重构为MVP架构 我的代码大致如下所示: public interface View { Presenter getPresenter(); } public abstract class Presenter { // Dagger 1 can't have an abstract class without injectable members... :( @Inject Application dont_n
public interface View {
Presenter getPresenter();
}
public abstract class Presenter {
// Dagger 1 can't have an abstract class without injectable members... :(
@Inject
Application dont_need_this;
protected View view;
public void takeView(View view) { ... }
}
Presenter中的字段并不漂亮,但我们能做些什么
接下来,我有一个活动,也是一个视图
现在一切似乎都很好
public abstract class MVPApplication extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Root scope
// createRootModules is defined in the subclass
objectGraph = ObjectGraph.create(createRootModules());
objectGraph.inject(this);
}
public abstract ObjectGraph createScope(View view);
}
因此,我的应用程序子类必须:
定义createRootModules以实例化根范围中的每个模块
在createScope中检查具体ActivityView的类,本质上使用HashMap再次查看,这是我的错
我不知道我为什么这么做,可能是为了避免将模块标记为不完整或库,但MyAppModule声明它正在注入CollectionActivityView,因此在添加其他模块之前,必须在该模块中解决Presenter依赖关系。将其从MyAppModule中的注释中删除,所有操作都按预期进行。如果使用plus,则需要在正在添加的@Module上添加addsTo。如果我对你的情况理解正确的话,那就是@Module{…,addsTo=modulefortissiactivityviewclass.class,…}我不这么认为,addsTo放在正在加积的模块中,不是吗?很难用语言来解释,但是是的。addsTo进入您正在加脉冲的@Module。如果您想拥有它的依赖项,那么plused模块是ObjectGraph中当时最顶层的模块。这有意义吗?哈哈,是的,当然D CollectionModule确实添加到了MyAppModule中,所以我认为这已经包括在内了。
public abstract class MVPApplication extends Application {
private ObjectGraph objectGraph;
@Override
public void onCreate() {
super.onCreate();
// Root scope
// createRootModules is defined in the subclass
objectGraph = ObjectGraph.create(createRootModules());
objectGraph.inject(this);
}
public abstract ObjectGraph createScope(View view);
}
return objectGraph.plus(new CollectionModule());
@Module(addsTo = MyAppModule.class,
injects = {CollectionActivityView.class, CollectionPresenter.class}, complete=false)
public class CollectionModule {
@Provides
@Singleton
public Presenter providePresenter(CollectionPresenter presenter) {
return presenter;
}
}
ComponentInfo{com.mycompany.myapp/com.mycompany.myapp.view.CollectionActivityView}:
java.lang.IllegalStateException: Unable to create binding for
com.mycompany.myapp.mvp.presenter.Presenter
...
Caused by: java.lang.IllegalStateException: Unable to create binding for
com.mycompany.myapp.mvp.presenter.Presenter
at dagger.internal.Linker.linkRequested(Linker.java:147)
at dagger.internal.Linker.linkAll(Linker.java:109)
at dagger.ObjectGraph$DaggerObjectGraph.linkEverything(ObjectGraph.java:244)
at dagger.ObjectGraph$DaggerObjectGraph.plus(ObjectGraph.java:203)