gpt4 book ai didi

android - Dagger 2 : Unable to inject singleton in other scope

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:55:00 25 4
gpt4 key购买 nike

我有 Singleton 作用域模块,它提供一些标准的单例:应用程序、数据库服务等。但是对于 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);
}

我做错了什么?

最佳答案

What am I doing wrong?

这个:

@ViewScope
@Component(modules = {SplashModule.class /*View scoped*/,
ApplicationModule.class/*Singleton scoped*/})

您只能在您的组件中包含未作用域或作用域与相同作用域的模块。您将需要使用多个组件。

要包含应用程序的依赖项,您需要将它们放在不同的组件中,例如应用组件。如果您这样做,您有 2 个选择:将 SplashComponent 声明为 ApplicationComponentSubComponent 或将 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com