匕首2具有相同依赖性的多个组件

问题描述:

我是新来的依赖注入,我甚至不确定这是否是正确的方法。匕首2具有相同依赖性的多个组件

我想要做的是让2个不同的组件共享相同的依赖关系。例如,我有我的彩票分量+其作为模块:

@PerActivity 
@Component(dependencies = NetworkComponent.class, 
     modules = { 
       LotteryModule.class 
     }) 
public interface LotteryComponent { 
    void inject(DashboardFragment fragment); 

    LotteryApiInterface lotteryApiInterface(); 
} 

@Module 
public class LotteryModule { 

    @Provides 
    @PerActivity 
    public LotteryApiInterface providesLotteryApiInterface(Retrofit retrofit) { 
     return retrofit.create(LotteryApiInterface.class); 
    } 
} 

,这里是消费分量+其模块:

@PerActivity 
@Component(dependencies = NetworkComponent.class, modules = SpendingModule.class) 
public interface SpendingComponent { 
    void inject(DashboardFragment fragment); 

    SpendingApiInterface spendingApiInterface(); 
} 


@Module 
public class SpendingModule { 

    @Provides 
    @PerActivity 
    public SpendingApiInterface providesSpendingApiInterface(Retrofit retrofit) { 
     return retrofit.create(SpendingApiInterface.class); 
    } 
} 

这有可能对那些2个组件共享一个相同的依赖?如何实现这个最好的方法?

谢谢

是的,这是可能的2个组件共享相同的依赖,但要确保的依赖是不是多余的。

在你的情况下,我没有看到创建两个组件的好处,而是你可以创建一个组件和一个模块,它将返回LotteryApiInterface或SpendingApiInterface服务。

如果LotteryApiInterface或SpendingApiInterface服务不在其他地方使用DashboardFragment,那么您可以将组件作为NetworkComponent的子组件,这样做无需在Component中公开您的依赖关系。

防爆

@PerActivity 
@Subcomponent(modules = LotterySpendingModule.class) 
public interface LotterySpendingComponent { 
    void inject(DashboardFragment fragment); 
} 

和NetworkComponent

public interface NetworkComponent { 
    LotterySpendingComponent plus(LotterySpendingModule module); 
} 
+0

感谢为协噶尔的答复。它将用于其他活动以及仪表板。但是,当我分离组件时,我很难添加依赖关系 –

+0

你能发表一些代码提到你正在面临的问题吗? – shekar