Dagger2 component with more than one dependencies

后端 未结 5 1313
轻奢々
轻奢々 2021-01-04 09:24

This is what I currently have and it works:

@FragmentScope
@Component(dependencies = {FacebookComponent.class}, 
            


        
5条回答
  •  伪装坚强ぢ
    2021-01-04 09:59

    What you want to be determined to be within the ApplicationScope should be all defined without a scope, and linked together under the application scope only in the ApplicationComponent under the given scope.

    For example,

    @Component(modules = {FacebookModule.class})
    public interface FacebookComponent {
        FacebookThing facebookThing(); //assuming this is with @Provides in FacebookModule with NO SCOPE
    }
    
    
    @Component(modules = {AnotherModule.class})
    public interface AnotherComponent{
        AnotherThing anotherThing(); //assuming this is with @Provides in AnotherModule with NO SCOPE
    }
    

    Then you can do

    @AppScope
    @Component(dependencies={AnotherComponent.class, FacebookComponent.class})
    public interface AppComponent extends AnotherComponent, FacebookComponent {}
    

    After which you can do

    @FragmentScope
    @Component(dependencies=AppComponent.class)
    public interface FragmentComponent extends AppComponent {}
    

    Please note that unscoped providers create a new instance on every inject call. If you need the scoping, you should bind the modules to the same component, but components should only depend on other components with the intention of subscoping.

提交回复
热议问题