2016-03-03 60 views
8

我有這樣的組成:Dagger2:錯誤時兩種組分具有相同的注入方法簽名

@Singleton 
@Component(modules = OauthModule.class) 
public interface OauthComponent { 

    void inject(LoginActivity a); 

} 

和模塊:

@Module 
public class OauthModule { 

    @Provides 
    @Singleton 
    Oauth2Service provideOauth2Service() { 
     return new Oauth2StaticService(); 
    } 

} 

並且該另一組件:

@Singleton 
@Component(modules = LoggedUserModule.class) 
public interface LoggedUserComponent { 

    void inject(LoginActivity a); 

} 

和我得到這個錯誤:

Error:(15, 10) error: Oauth2Service cannot be provided without an @Provides- or @Produces-annotated method.

如果我改變LoggedUserComponent的注射方法的參數是另一個Activity,說AnotherActivity這樣的:

@Singleton 
@Component(modules = LoggedUserModule.class) 
public interface LoggedUserComponent { 

    void inject(AnotherActivity a); 

} 

編譯就可以了。爲什麼?我不能有兩個組件具有相同的注入簽名嗎?

我想了解Dagger如何工作,所以任何幫助將不勝感激。謝謝。

回答

7

dagger覺得作爲一個對象圖—它實際上是。您可能應該而不是有2個不同的組件可以注入相同的對象,除了用於測試目的(或者如果你想包括不同的行爲,而不是另外的行爲)。

如果您LoginActivity取決於多個模塊,您應該彙總他們在一個單一的組成部分,因爲隨着你的錯誤顯示,如果它不能從單個組件提供所有依賴匕首將失敗。

@Singleton 
@Component(modules = {LoggedUserModule.class, OauthModule.class}) 
public interface LoggedUserComponent { 

    void inject(AnotherActivity a); 

} 

看着Oauth2Service,這很容易被一些多個對象可以使用,因此較高的範圍可以是足夠的。在這種情況下,您應該考慮將其與@Singleton範圍一起添加到您的應用程序組件中,或者可以使用例如創建自己的組件。一個@UserScope

那麼你就必須要麼讓你LoggedUserComponent一個@Subcomponent或聲明該組件採用@Component(dependencies = OauthComponent.class),並提供在OauthComponent它獲取方法的依賴。在這兩種情況下,匕首也能夠提供圖中較高的依賴關係,從而也解決了您的錯誤。

0

它變得生氣,因爲你說你可以注入到這個類中,但是你沒有提供它期望你提供的類。您只需將OauthModule添加到LoggedUserComponent。試試這個

@Singleton 
@Component(modules = {LoggedUserModule.class, OauthModule.class}) 
public interface LoggedUserComponent { 

    void inject(LoginActivity loginActivity); 

} 
+0

如果我的OAuthModule是單例呢?我將永遠無法注射? – sector11

+0

我不確定我是否按照你的要求 – ootinii

相關問題