2015-04-23 67 views
1

對於Dagger2發佈,我打算將模塊拆分成幾個小模塊以供其他項目重用。Dagger2多模塊設計

應用程序模塊包含很多東西,我可以將它分爲三種類型。 類型A相關,類型B相關,類型C相關。

所以我想把它放到三個不同的模塊中,因此如果需要在其他項目上它可以重新使用它的一部分。從Google's Fork

的build.gradle的應用

buildscript { 
repositories { 
    jcenter() 
} 
dependencies { 
    classpath 'com.android.tools.build:gradle:1.1.0' 
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' 

    // NOTE: Do not place your application dependencies here; they belong 
    // in the individual module build.gradle files 
    } 
} 
allprojects { 
    repositories { 
     mavenCentral() 
    } 
} 

的build.gradle的應用模塊

apply plugin: 'com.neenbedankt.android-apt' 
//below lines go to dependenc 
compile 'com.google.dagger:dagger:2.0' 
apt 'com.google.dagger:dagger-compiler:2.0' 
provided 'org.glassfish:javax.annotation:10.0-b28' 
上述步驟後

參考,我要創造我的應用模塊

@dagger.Module 
public class MyApplicationModule { 
    void inject(MyApplication application); 
} 

和我的組件

@Singleton 
@Component(
     modules = {TypeA.class, TypeB.class, TypeC.class}) 
public interface MyApplicationComponent { 

當我使用它的活動,它看起來像

@Component(dependencies = MyApplicationComponent.class, 
     modules = ActivityModule.class) 
public interface ActivityComponent { 

    void injectActivity(SplashScreenActivity activity); 

有編譯問題

Error:(22, 10) error: XXXXXX cannot be provided without an @Provides- or @Produces-annotated method. com.myapplication.mXXX [injected field of type: XXX]

我想有什麼不對,當我配置該Activity組件從應用程序組件擴展而來。

我的目的是應用程序組件內的一些單例對象,活動將注入同一對象以減少每次活動時創建的某個對象。 是我的設計錯誤?或任何其他的事情需要配置?

回答

1

找出病根來自@Scope

必須暴露於其他子組件的使用

@Scope 
@Retention(RetentionPolicy.RUNTIME) 
public @interface ActivityScope { 
} 

的類型,如果我們想要展示的應用程序的上下文,

@Singleton 
@Component(
     {TypeA.class, TypeB.class, TypeC.class}) 
public interface MyApplicationComponent { 

    void inject(MyApplication application); 

    @ForApplication 
    Context appContext(); 

當我的子組件想要擴展這個

@ActivityScope 
@Component(dependencies = MyApplicationComponent.class, 
     modules = ActivityModule.class) 
public interface ActivityComponent extends MyApplicationComponent { 

    void injectActivity(Activity activity); 

我認爲這對於Dagger2是一件好事,讓你手動暴露你需要使用的對象,代碼變得更加可追蹤。