使用Dagger和Android MVP模式时如何注入上下文?

9
在开发Android应用程序时,我遇到了一个问题。我刚开始使用Dagger,所以我知道一些基本概念,但是当在教程之外使用它时,事情变得不太清楚。
因此,为了进入正题。在我的应用程序中,我正在使用MVP,如此博客文章中所述:http://antonioleiva.com/mvp-android/ 所以起初我将Interactor类(处理数据的类)注入到Presenter类中,一切都很好。但是后来我实现��使用SQLite数据库的方法,因此现在需要在我的Interactor类中使用Context。
我无法弄清楚应该如何正确地做这件事?我的临时解决方案是从我的应用程序中排除Dagger,并在创建Presenter类和Presenter内部的Interactor类时通过构造函数传递Context变量,但我想使用Dagger。
因此,我的当前应用程序看起来有点像这样。
MyActivity implements MyView {     
      MyPresenter p = new MyPresenter(this, getApplicationContext());
}

MyPresenter中的构造函数

MyPresenter(MyView view, Context context) {
      this.view = view;
      MyInteractor i = new MyInteractor(context);
}

MyInteractor的构造函数中,我将Context赋值给一个私有变量。我只需要将MyInteractor注入到MyPresenter中,因为这是应用程序的一部分,需要针对不同的实现进行测试。但如果也可以将MyPresenter注入到MyActivity中,那就太好了 :) 我希望有人能够对我所尝试实现的内容有些经验 :)
1个回答

6
在你的类 MyInteractor 中:
public class MyInteractor {

    @Inject
    public MyInteractor(Context context) {
       // Do your stuff...
    }
}

我的Presenter类

public class MyPresenter {
    @Inject
    MyInteractor interactor;

    public MyPresenter(MyView view) {
        // Perform your injection. Depends on your dagger implementation, e.g.
        OBJECTGRAPH.inject(this)
    }
}

为了注入一个上下文,您需要编写一个具有提供方法的模块:
@Module (injects = {MyPresenter.class})
public class RootModule {
    private Context context;

    public RootModule(BaseApplication application) {
        this.context = application.getApplicationContext();
    }

    @Provides
    @Singleton
    Context provideContext() {
        return context;
    }
}

将Presenter类注入到Activity中并不容易,因为在构造函数中有MyView参数,这个参数无法由Dagger设置。你可以通过在MyPresenter类中提供一个setMyView方法来重新考虑你的设计,而不是使用构造函数参数。

编辑:创建RootModule

public class BaseApplication extends Application {
    // Store Objectgraph as member attribute or use a Wrapper-class or...

    @Override
    public void onCreate() {
        super.onCreate();
        OBJECTGRAPH = ObjectGraph.create(getInjectionModule());
    } 

    protected Object getInjectionModule() {
        return new RootModule(this);
    }
}

你的 RootModule 如何获取 BaseApplication 的呢? - theblang
@mattblang:我已经在我的答案中添加了这部分内容。 - Christopher

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接