Search code examples
javaandroiddagger-2

Dagger2 component with more than one dependencies


This is what I currently have and it works:

@FragmentScope
@Component(dependencies = {FacebookComponent.class}, 
           modules = {FragmentFacebookLoginModule.class})
public interface FragmentFacebookLoginComponent {

    void inject(FragmentFacebookLogin fragment);
}

Now I want to add another dependency. I changed it to this:

@Component(dependencies = {FacebookComponent.class, AnotherComponent.class}, 
           modules = {FragmentFacebookLoginModule.class})

But now I get this error message:

FragmentFacebookLoginComponent depends on more than one scoped component

How can I solve this? How can I have more than one dependencies?

If I remove the scope from one component I get this error message:

AnotherComponent (unscoped) cannot depend on scoped components


Solution

  • I found the answer here: https://stackoverflow.com/a/29619594/1016472

    At the end I created a AppComponent with the right scope and let FacebookComponent and AnotherComponent extends this AppComponent.

    FacebookComponent and AnotherComponent does not have it's own scope (I removed it).

    Looks now like this:

    @AppScope
    @Component
    public interface AppComponent {
    
    }
    
    
    @Component(modules = {FacebookModule.class})
    public interface FacebookComponent extends AppComponent {
    
    }
    
    
    @Component(modules = {AnotherModule.class})
    public interface AnotherComponent extends AppComponent {
    
    }
    
    
    @FragmentScope
    @Component(dependencies = {FacebookComponent.class, AnotherComponent.class}, 
               modules = {FragmentFacebookLoginModule.class})
    public interface FragmentFacebookLoginComponent {
    
        void inject(FragmentFacebookLogin fragment);
    }