Android Dagger 2跨模块依赖关系

Android Dagger 2跨模块依赖关系,android,dependency-injection,dagger-2,Android,Dependency Injection,Dagger 2,在我当前的项目中,我们有一个应用程序组件,它包含各种模块,包括网络模块: DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .networkModule(new NetworkModule()) .apiModule(new ApiModule()) .build(); @Module public class NetworkModule ex

在我当前的项目中,我们有一个
应用程序组件
,它包含各种模块,包括
网络模块

DaggerApplicationComponent.builder()
    .applicationModule(new ApplicationModule(this))
    .networkModule(new NetworkModule())
    .apiModule(new ApiModule())
    .build();
@Module
public class NetworkModule extends BaseNetworkModule {
    HttpLoggingInterceptor.Level getHttpLoggingInterceptorLevel() {
        return HttpLoggingInterceptor.Level.BODY;
    }
}
现在我想设置一个
UserServices
模块,该模块将至少提供一个
UserServices
对象,该对象需要其他模块提供的一些配置。例如,
NetworkModule
提供了一个
HttpLoggingInterceptor.Level
,用于应用程序中的其他网络调用,我希望在
UserServices
调用中使用同样的功能

网络模块的调试版本示例:

DaggerApplicationComponent.builder()
    .applicationModule(new ApplicationModule(this))
    .networkModule(new NetworkModule())
    .apiModule(new ApiModule())
    .build();
@Module
public class NetworkModule extends BaseNetworkModule {
    HttpLoggingInterceptor.Level getHttpLoggingInterceptorLevel() {
        return HttpLoggingInterceptor.Level.BODY;
    }
}
为了封装,我想将
UserServices
提供的内容保留在自己的模块中

如何设置
UserServices
模块,使其可以包含在同一组件中,并可以访问
NetworkModule
中提供的来配置它提供的
UserServices
对象


谢谢

您可以将网络模块作为依赖项添加到UserServices模块,或将网络组件作为依赖组件添加到UserServices组件。如果作为依赖组件添加,您将不得不在网络组件中提及提供商。

我通过一些尝试和错误找到了答案。如果依赖模块未包含在
组件中
,则我可以简单地将
包含
参数添加到
@module
注释中:

@Module(includes= {
        NetworkModule.class,
        ApiModule.class
    })
在我的例子中,依赖模块和其他一些模块在多个地方使用,并且在
组件
本身中都是独立需要的。幸运的是,Dagger似乎可以在同一个组件的模块之间为我连接东西。因此,在这种情况下,我真的不需要做任何特殊的事情——只需在组件中执行以下操作:

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