android – Dagger 2:组件依赖于多个作用域组件

我是Dagger 2的新手.我正在尝试在我的 Android项目中实现它.
我有一个需要Googleapiclient的服务.我正在使用Dagger将其注入此服务中.
@FragmentScoped
@Component(dependencies = {NetComponent.class,RepositoryComponent.class})
public interface CustomServiceComponent {
    void inject(CustomService customService);
}

@Singleton
@Component(modules = {AppModule.class,NetModule.class})
public interface NetComponent {
    Googleapiclient getGoogleapiclient();
}

@Singleton
@Component(modules = {AppModule.class,RepositoryModule.class})
public interface RepositoryComponent {
    DatabaseService getDatabaseService();
}

AppModule,NetModule和RepositoryModule都有标记@Singleton @Provides的方法
当我构建我的项目时,我收到此错误

The locationServiceComponent depends on more than one scoped
component: @Singleton NetComponent @Singleton RepositoryComponent

我理解我的LocationComponent不能依赖于两个@Singleton作用域组件,但我需要在我的服务中同时使用它们,并且都需要@Singleton.

做同样的事还有更好的选择吗?

解决方法

请注意,虽然您可能有多个标记为@Singleton的组件,但它们的生命周期将遵循保留组件引用的类的生命周期.

这意味着如果在Activity中初始化并保留NetComponent和RepositoryComponent,它将遵循该Activity的生命周期,并且不会真正成为应用程序单例.

因此,在Android应用中,您可能不需要多个@Singleton组件.考虑将两个Singleton组件组合成一个组件,如下所示:

@Component(modules = {AppModule.class,NetModule.class,RepositoryModule.class})
@Singleton
public interface AppComponent {
    Googleapiclient getGoogleapiclient();

    DatabaseService getDatabaseService();
}

然后确保在应用程序级别保留此@Singleton组件,并使其可用于在Fragment或Activity级别初始化的从属组件.

public class MyApp extends Application {

    private final AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.builder()
                           //modules if necessary
                           .build();
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }                   
}

请注意,只要您的@FragmentScoped本身没有任何依赖组件,您仍然可以根据需要创建任意数量的组件.

请注意,即使单个组件现在注入了Googleapiclient和DatabaseService,您仍然可以分离关注点,因为这些是在单独的Dagger 2模块中提供的.

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...