alphonzo79
alphonzo79

Reputation: 928

Dagger 2 Cross-Module Dependency

In my current project we have an ApplicationComponent, which holds various modules including a NetworkModule:

DaggerApplicationComponent.builder()
    .applicationModule(new ApplicationModule(this))
    .networkModule(new NetworkModule())
    .apiModule(new ApiModule())
    .build();

I now want to setup a UserServices module that will provide at least a UserServices object, and that object requires some of the provides from the other modules for configuration. For example, the NetworkModule provides an HttpLoggingInterceptor.Level that is used for other network calls in the app, and I would like to use the same in the UserServices calls.

Example from the debug version of the NetworkModule:

@Module
public class NetworkModule extends BaseNetworkModule {
    HttpLoggingInterceptor.Level getHttpLoggingInterceptorLevel() {
        return HttpLoggingInterceptor.Level.BODY;
    }
}

I want to keep the UserServices provide in its own module for the sake of encapsulation.

How do I set up the UserServices module so it can be included in the same component, and have access to the Provides in the NetworkModule for configuring the UserServices object that it provides?

Thanks

Upvotes: 3

Views: 3196

Answers (2)

alphonzo79
alphonzo79

Reputation: 928

I figured this out through a little trial and error. If the dependency module is not included in the component already then I can simply add the includes parameter to the @Module annotation:

@Module(includes= {
        NetworkModule.class,
        ApiModule.class
    })

In my case, the dependency module and some others are used in several places and all are needed independently in the component itself. Fortunately, it appears that Dagger will wire stuff up for me across modules in the same component. So I really didn't need to do anything special in this case -- Just this in the component:

@Singleton
@Component(modules = {
            ApplicationModule.class,
            NetworkModule.class,
            SchedulerModule.class,
            ApiModule.class,
            UserServicesModule.class
    })

Upvotes: 2

user3215142
user3215142

Reputation: 326

You can add Network module as dependency to your UserServices module or add Network component as dependent component to UserServices component. If added as dependent component you'll have to mention the provider in Network component.

Upvotes: 0

Related Questions