多个库项目中共享依赖项的匕首组织?

Dagger organization for shared dependencies in multiple library projects?

跨库项目共享依赖项的最佳方式是什么?我想保持它们的独立性,只是有一些东西可以明确地告诉组件它需要什么,以及它将在内部提供什么的模块。

我可以让所有库都提供一个模块,父应用程序可以将其添加到其组件中,但是如果多个模块提供相同的东西,Dagger 将(正确地)出错。

我想我明白了:

库模块提供了它们所需的依赖项DependencyInterface 的接口。在内部,他们将使用自己的组件,该组件依赖于 DependencyInterface.

集成应用程序只需要提供自己的 "implementation" 界面。如果他们自己正在使用 Dagger,那么 AppComponent 将只实现接口并让 Dagger 提供依赖项。

例如:

库组件端:

@Component(
        modules = {
                // your internal library modules here.
        },
        dependencies = {
                LibraryDependencies.class
        }
)

public interface LibraryComponent {
    // etc...
}

public interface LibraryDependencies {

    // Things that the library needs, etc.
    Retrofit retrofit();

    OkHttpClient okHttpClient();
}

对于集成应用端:

@Singleton
@Component(
        modules = {
                InterfaceModule.class,
                // etc...
        }
)
public abstract class IntegratingAppComponent implements LibraryDependencies {
    // etc...
}


/**
 * This module is just to transform the IntegratingAppComponent into the interfaces that it
 * represents in Dagger, since Dagger only does injection on a direct class by class basis.
 */

@Module
public abstract class InterfaceModule {

    @Provides
    public static LibraryDependencies providesLibraryDependencies(IntegratingAppComponent component) {
        return component;
    }
}