我遇到类似this问题中的问题。 虽然接受的答案确实有帮助,但我错过了最后一块来解决问题。匕首 - 在不同组件上获取相同的实例
我有2个android库模块:common
和exp
这取决于common
。
common
下
一切:
@Module
public class CommonModule {
@Singleton
@Provides
public Repository providesRepository() {
return new Repository();
}
}
@Singleton
@Component(modules={CommonModule.class})
public interface CommonComponent {
void inject(CommonClass commonClass);
/**
CommonClass needs instance of Repository
**/
}
public class CommonDIHolder {
public static CommonComponent sComponent;
public static void init() {
sComponent = DaggerCommonComponent.builder().build();
}
}
一切下exp
:
@Module(includes={CommonModule.class})
public class ExpModule {
@Singleton
@Provides
public ExpResource provideExpResource() {
return new ExpResource();
}
}
@Singleton
@Component(modules={ExpModule.class}, dependencies={CommonComponent.class})
public interface ExpComponent {
void inject(ExpClass expClass);
/**
ExpClass needs instance of Repository and ExpResource
**/
}
public class ExpDIHolder {
public static ExpComponent sComponent;
public static void init() {
sComponent = DaggerExpComponent.builder()
.commonComponent(CommonDIHolder.sComponent)
.build();
}
}
我同时需要CommonClass
和ExpClass
收到的Repository
相同的实例。
此方法的问题是@Singleton
不能取决于@Singleton
。所以我必须将ExpComponent
的范围改为自定义范围@ExpScope
。然后我将provideExpResource
更改为@ExpScope
。
然后我遇到一个错误,说ExpComponent
可能不会引用与不同作用域的绑定。它指的是provideRepository
,它有不同的范围(@Singleton
)。如果我将范围更改为ExpScope
,那么CommonComponent
与provideRepository
的范围将有所不同。
如果我改变了所有@Singleton
为@ExpScope
然后我收到此错误信息:depends on scoped components in a non-hierarchical scope ordering
我该怎么办?或者我在这里做错了方法?
的Android项目的良好的工作实例“因此,我必须将ExpComponent的范围改为自定义范围,称为** ExpScope **,然后将provideExpResource更改为** ExpScope **以及”Works正常用这个设置。使用匕首2.10。 – azizbekian