Dagger with Android:如何在使用MVP时注入上下文?

Den*_*tez 9 java mvp android dagger

在开发Android应用程序时,我偶然发现了一个问题.我刚刚开始使用Dagger,所以我知道一些基本概念,但是当在教程范围之外使用它时,它们的用例变得不那么清楚了.

所以要明白这一点.在我的应用程序中,我正在使用MVP,如本博客文章中所述:http://antonioleiva.com/mvp-android/

所以起初我将Interactor类(处理数据的类)注入Presenter类,一切正常.但后来我实现了使用SQLite数据库的方法,所以现在需要在我的Interactor类中使用Context.

我无法弄清楚我该如何正确地做到这一点?我的临时修复是将Dagger从我的应用程序中排除,并在创建Presenter类时在构造函数中传递Context变量,然后在presenter中传递Interactor类,但我想使用Dagger.

所以我目前的应用看起来有点像这样.

MyActivity implements MyView {     
      MyPresenter p = new MyPresenter(this, getApplicationContext());
}
Run Code Online (Sandbox Code Playgroud)

MyPresenter中的构造函数

MyPresenter(MyView view, Context context) {
      this.view = view;
      MyInteractor i = new MyInteractor(context);
}
Run Code Online (Sandbox Code Playgroud)

在构造函数中MyInteractor我分配Context给一个私有变量.

我只需要注入MyInteractorMyPresenter,因为这是应用程序,需要针对不同的实现进行测试的一部分.但是,如果它也将是可以注入MyPresenterMyActivity,那将是巨大的:)

我希望有人对我想要实现的目标有一些经验:)

Chr*_*her 6

在你的类MyInteractor中:

public class MyInteractor {

    @Inject
    public MyInteractor(Context context) {
       // Do your stuff...
    }
}
Run Code Online (Sandbox Code Playgroud)

MyPresenter级

public class MyPresenter {
    @Inject
    MyInteractor interactor;

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

要注入Context,您需要使用provide方法编写一个模块:

@Module (injects = {MyPresenter.class})
public class RootModule {
    private Context context;

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

    @Provides
    @Singleton
    Context provideContext() {
        return context;
    }
}
Run Code Online (Sandbox Code Playgroud)

将Presenter类注入到您的活动中并不容易,因为在您的构造函数中,您有此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);
    }
}
Run Code Online (Sandbox Code Playgroud)