2016-08-13 111 views
1

我是新來的依賴注入,我甚至不確定這是否是正確的方法。匕首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個組件共享一個相同的依賴?如何實現這個最好的方法?

謝謝

回答

1

是的,這是可能的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