大佬教程收集整理的这篇文章主要介绍了android – Dagger 2:组件依赖于多个作用域组件,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@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的方法@H_404_2@当我构建我的项目时,我收到此错误:
我理解我的LOCATIOnComponent不能依赖于两个@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 – Dagger 2:组件依赖于多个作用域组件全部内容,希望文章能够帮你解决android – Dagger 2:组件依赖于多个作用域组件所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。