Problems with singletons when using component dependencies

前端 未结 3 1187
猫巷女王i
猫巷女王i 2020-12-24 04:48

I\'m having a problem in understanding why the following code doesn\'t work.

I have following project structure:

@Component(modules = CCModule.class)         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 05:49

    You should put @Singletonto CComponent class declaration.

    @Singleton
    @Component(modules = CCModule.class) 
    public interface CComponent {
        XXX getXXX();
    }
    

    Explanation is in error message: CComponent is unscoped, @Singleton is a scope. Dagger 2 does not allow unscoped components to use modules with scoped bindings.
    However, now you will get the following error:

    AComponent (unscoped) cannot depend on scoped components:
    @Component(dependencies = CComponent.class, modules = AModule.class)
    

    Unscoped components cannot have scoped dependencies. So you need to make AComponent scoped. To do this create custom AScope annotation.

    @Scope
    @Retention(RetentionPolicy.RUNTIME)
    public @interface AScope {
    }
    

    And annotate with it AComponent:

    @AScope
    @Component(dependencies = CComponent.class, modules = AModule.class)
    public interface AComponent {
    }
    

    These are new requirements appeared in latest snapshot release. It was discussed in corresponding issue and may still be changed.

提交回复
热议问题