我正在使用 Dagger,并且我有一个具有 @Singleton
作用域的应用程序组件以及一个具有 @Singleton
作用域的子组件。现在,当我编译它时,我得到了这个错误:
[io.droid.nowtellapp.dagger.SignInMvpComponet] io.droid.nowtellapp.dagger.SignInMvpComponet has conflicting scopes: io.droid.nowtellapp.dagger.ApplicationComponent also has @Singleton
为了解决这个错误,我从我的子组件中删除了 @Singleton
并编译了它,这次得到了这个错误:
Error:(12, 1) error: io.droid.nowtellapp.dagger.SignInMvpComponet (unscoped) may not reference scoped bindings: @Singleton @Provides io.droid.nowtellapp.mvp.SignInMvp.Presenter io.droid.nowtellapp.dagger.SignInMvpModule.presenter(io.droid.nowtellapp.webservices.NowTellApi)
同样出现这个错误:
Error:(21, 8) error: [ComponentProcessor:MiscError] dagger.internal.codegen.ComponentProcessor was unable to process this class because not all of its dependencies could be resolved. Check for compilation errors or a circular dependency with generated code.
这是我的应用组件
@Singleton
@Component(modules = {AppModule.class, RetroApiModule.class})
public interface ApplicationComponent {
void inject(MainActivity mainActivity);
SignInMvpComponet signInMvpComponet(SignInMvpModule signInMvpModule);
}
这是我的 SignInMvpComponet
@Subcomponent(modules = {SignInMvpModule.class})
public interface SignInMvpComponet {
void inject(SignInFragment signInFragment);
这是 SignInMvpModule 类
@Module
public class SignInMvpModule {
private final SignInMvp.View view;
public SignInMvpModule(SignInMvp.View view) {
this.view = view;
}
@Singleton
@Provides
SignInMvp.Presenter presenter(NowTellApi api) {
return new SignInPresenter(view,api);
}
}
如何解决这个问题?提前致谢。
最佳答案
I have an app component with @Singleton scope and also a subcomponent with @Singleton scope.
不,你不知道。子组件不能与其父组件具有相同的范围。你可以阅读in the documentation :
No subcomponent may be associated with the same scope as any ancestor component, although two subcomponents that are not mutually reachable can be associated with the same scope because there is no ambiguity about where to store the scoped objects.
您的第一个错误是因为父组件和子组件共享相同的作用域,您的第二个错误是因为子组件需要 一个作用域。这两个错误的解决方案是给子组件一个不同于父组件的范围,或者根本不使用子组件(如果它们都应该是 @Singleton
,为什么需要 2?)
通常我们倾向于为我们的子组件创建像 @PerActivity
或 @ActivityScoped
这样的作用域,它们共享(正如名称所示)Activity 的生命周期并获取在其中使用。
关于java - Dagger 组件有冲突的作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48473699/