我有Singleton作用域模块,它提供一些标准的Singleton:应用程序,DB服务等。
但是对于Activity我有一个单独的模块,应该为Activity创建Presenter,并且我需要将Application上下文传递给它。但是,在尝试编译项目时出现以下错误:
Error:(13, 1) error: xxx.SplashComponent scoped with @xxx.ViewScope may not reference bindings with different scopes:
@Provides @Singleton xxx.ApplicationModule.provideAppContext()
这是我的应用程序模块的 fragment :
@Singleton
@Module
public class ApplicationModule {
private Application app;
public ApplicationModule(Application app) {
this.app = app;
}
@Provides
@Singleton
@Named("ui")
Scheduler provideUIScheduler() {
return AndroidSchedulers.mainThread();
}
@Provides
@Singleton
@Named("io")
Scheduler provideIOScheduler() {
return Schedulers.io();
}
@Provides
@Singleton
Application provideApplication() {
return app;
}
@Provides
@Singleton
Context provideAppContext() {
return app;
}
}
这是 Activity 模块和组件:
@Module
public class SplashModule {
private final FragmentManager fragmentManager;
public SplashModule(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
@Provides
@ViewScope
Presenter getPresenter(Context context) {
return new SplashPresenter(context, fragmentManager);
}
}
成分:
@ViewScope
@Component(modules = {SplashModule.class, ApplicationModule.class})
public interface SplashComponent {
void inject(SplashActivity activity);
}
我究竟做错了什么?
最佳答案
这:
@ViewScope
@Component(modules = {SplashModule.class /*View scoped*/,
ApplicationModule.class/*Singleton scoped*/})
您只能在组件中包括作用域相同的无作用域的模块或模块。您将需要使用多个组件。
要包括应用程序中的依赖项,您需要将它们置于不同的组件中,例如
ApplicationComponent
。如果要执行此操作,则有两种选择:要么将SplashComponent
声明为SubComponent
的ApplicationComponent
,要么将ApplicationComponent
添加为组件的依赖项。如果将其添加为依赖项,请确保还在ApplicationComponent
中提供方法,以便它可以访问依赖项。例如如果要使用组件依赖项:
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(MyApplication app);
// todo: also add getters for your other dependencies you need further down the graph
Application getApplication();
}
@Component(modules = {SplashModule.class}, dependencies={ApplicationComponent.class})
public interface SplashComponent {
// as before
}
关于android - Dagger 2 : Unable to inject singleton in other scope,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35972270/