Bruno Neuman
Bruno Neuman

Reputation: 148

Dagger2 - Cross-Module Dependecy

I'm trying to build a simple cross-module dependency with Dagger2.

When I rebuild the project, all DaggerComponents go down.

I have the genereal application dependency injection package for the Application:

Component - General DI

@Singleton
@Component( modules = { MyAppModule.class } )
public interface MyAppComponent {

    void inject( MyApp application );
}

Module - General DI

@Module
public class MyAppModule {

    private MyApp mMyApp;

    public MyAppModule( MyApp application ) {
        mMyApp = application;
    }

    @Singleton
    @Provides
    public Application provideApplication() {
        return mMyApp;
    }

    @Singleton
    @Provides
    public SharedPreferences provideSharedPreferences( MyApp application ) {
        return PreferenceManager.getDefaultSharedPreferences( application );
    }

    @Singleton
    @Provides
    public MyDatabase provideMyDatabase() {
        return new MyDatabase();
    }

    @Singleton
    @Provides
    public MyRepositoryContract provideMyRepository( MyDatabase database, SharedPreferences sharedPreferences ) {
        return new MyRepository( database, sharedPreferences );
    }
}

I have a layer called Main that need use MyRepository, but when I try do the Dependency, all go down.

Component - Main DI ( MyApp Dependency )

@MainScope
@Component( dependencies = { MyAppModule.class },  // <- Contains requested provider
            modules = { MainModule.class } )
public interface MainComponent {

    void inject( MainActivity view );
}

Module - Main DI ( MyApp Dependency )

@Module( includes = { MyAppModule.class } )  // <- Contains requested provider
public class MainModule {

    private final MainContract.View mView;

    @MainScope
    public MainModule( MainContract.View view ) {
        mView = view;
    }

    @MainScope
    @Provides
    public MainContract.Model provideModel( MyRepositoryContract repository ) { 
        return new MainModel( repository ); // <- My requested object from MyApp DI package
    }

    @MainScope
    @Provides
    public MainContract.View provideView() {
        return mView;
    }

    @MainScope
    @Provides
    public MainContract.Presenter providePresenter( MainContract.Model model, MainContract.View
            view ) {
        return new MainPresenter( model, view );
    }
}

MainScope - Main DI ( MyApp Dependency )

@Scope
@Retention( RetentionPolicy.RUNTIME )
@interface MainScope {
}

Upvotes: 0

Views: 334

Answers (1)

Daniel
Daniel

Reputation: 143

The @Component annotation is already defined in MyAppComponent, all short lived components use @SubComponent as they build on the top of higher-level components. This is happening because there is another declaration of @Component annotation in theMainComponent file, try to use @Subcomponent annotation for that file.

Upvotes: 1

Related Questions