如何为其他片段提供匕首依赖?

How to provide dagger dependency for other fragments?

我有 ApplicationComponent 提供 ApiModule 和其他

@PerApplicationScope
@Component(
        modules = {ApiModule.class, ApplicationModule.class}
)
public interface ApplicationComponent {

    void inject(MainActivity activity);
}

我在应用程序启动时构建此组件:

@Override
public void onCreate() {
    super.onCreate();

    component = DaggerApplicationComponent.builder()
            .applicationModule(new ApplicationModule(this))
            .apiModule(new ApiModule())
            .build();
}

只有在我的初始片段加载并且我从某些 API 响应中获得响应后,我才能创建应该在所有其他片段之间共享的 Player

如何告诉 Dagger 有新模块和新依赖项?

使用 Dagger,您可以使用组件范围,如果您想要在整个应用程序生命周期中使用相同的对象实例,则必须在应用程序级组件中将依赖项作为 @Singleton 提供。

您可以为 Activity 片段创建自定义范围,使用自定义注释在该图形生命周期中提供相同的 ApiModule 依赖项实例。

这里有一个使用 Dagger 作用域的示例项目

https://github.com/joesteele/dagger2-component-scopes-test

关于这个话题post

http://fernandocejas.com/2015/04/11/tasting-dagger-2-on-android/