2015-11-05 70 views
0

我剛從DI/Dagger 2開始。我有一個巨大的項目。爲了嘗試匕首2,我開始注入我的單例類'MyPreferences'。該類處理來自SharedPreferences的所有應用程序操作。匕首2:用很多接入點注入單身

自動注入MyPreferences中的SharedPreferences完美無缺。

不過,我在大約50類中使用這個單,我曾經這樣做:

MyPreferences.getInstance(context).getXXXSetting(); 

我已經在幾班改變這dagger2注射,並能正常工作,但我發現自己一直複製這些行:

@Inject 
protected MyPreferences myPreferences; 

protected void initInjection(Context context) { 
    ((RootApplicationDi) context.getApplicationContext()).getComponent().injectTo(this); 
} 

// + call initInjection @ onCreate/constructor 

對於這樣一個簡單的調用,我需要在大約35-40(超)類中的所有這些行。我錯過了什麼嗎?這真的是要走的路嗎?

+0

你有一個巨大的項目,工作正常...與一個單身。爲什麼改變它?通過切換到DI,您期望獲得什麼? (p.s. downvote不是我的) – ZhongYu

回答

0

我以前的答案是Dagger 1,因此不正確。下面是匕首2示例解決方案:

在您的應用程序類:

private MyDagger2Component mDependencyInjector; 


@Override 
public void onCreate() { 
    super.onCreate(); 

    mDependencyInjector = DaggerMyDagger2Component.builder()...build(); 
} 


public MyDagger2Component getDependencyInjector() { 
    return mDependencyInjector; 
} 

在你的基地Activity類的活動擴展:

protected MyDaggerComponent getDependencyInjector() { 
    return ((MyApplication) getApplication()).getDependencyInjector(); 
} 

而在你的活動,你現在可以有剛一行注射:

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    getDependencyInjector().inject(this); 
    ... 
}