2015-04-01 36 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

相關問題