Dagger 2: Unable to inject singleton in other scope

Viewed 11713

I have Singleton scoped module that provides some standard singletons: Application, DB services, etc. But for Activity I have separate module that should create Presenter for he Activity and I need to pass Application context to it. However I get following error when trying to compile the project:

Error:(13, 1) error: xxx.SplashComponent scoped with @xxx.ViewScope may not reference bindings with different scopes:
@Provides @Singleton xxx.ApplicationModule.provideAppContext()

Here is snippet of my Application module:

@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;
    }
}

And here is Activity module and Component:

@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);
    }
}

Component:

@ViewScope
@Component(modules = {SplashModule.class, ApplicationModule.class})
public interface SplashComponent {
    void inject(SplashActivity activity);
}

What am I doing wrong?

3 Answers

Scoping rules:

  • When a type is marked with a scope annotation, it can only be used by Components that are annotated with the same scope.
  • When a Component is marked with a scope annotation, it can only provide types with that annotation or types that have no annotation.
  • A subcomponent cannot use a scope annotation used by one of its parent Components.

Components also involve subcomponents in this context.

Caution:- Modules that use a scope annotation can only be used in components that are annotated with the same scope. Check Here.

For more information on Dagger in Android go through this training and practise it here.

Related