2015-04-01 35 views
8

在开发Android应用程序时,我偶然发现了一个问题。我刚开始使用Dagger,所以我知道一些基本概念,但在教程范围外使用它时,事情变得不那么清晰。Dagger with Android:如何在使用MVP时注入上下文?

所以要说到这一点。在我的应用程序中,我使用了本博客中描述的MVP:http://antonioleiva.com/mvp-android/

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

我不知道我该如何正确地做到这一点?我的临时解决方法是从应用程序中排除Dagger,并在创建Presenter类时在构造函数中传递Context变量,然后在Presenter中创建Interactor类,但我想使用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,因为这是需要针对不同实现进行测试的应用程序的一部分。但是,如果它也将是可能的注入MyPresenterMyActivity,那将是巨大的:)

我希望有人有我想要实现:)

回答

5

在你的类MyInteractor一些经验:

public class MyInteractor { 

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

MyPresenter级

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; 
    } 
} 

注入您的演示级到您的活动也不是那么容易,因为在你的构造你有这样的MyView的参数,它不能被匕首设置。您可以通过在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); 
    } 
} 
+0

它怎么说,你的'RootModule'可以得到'BaseApplication'? – theblang 2015-05-08 19:59:06

+0

@mattblang:我在回答中添加了这部分内容。 – Christopher 2015-05-11 06:18:48