2016-07-19 13 views
1

Dagger2には以下のような2つのモジュールから注入が可能ですか?複数のコンポーネントからのフィールド注入

public class MyActivity extends Activity { 

    @Inject ProvidedByOne one; 
    @Inject ProvidedByTwo two; 

    public void onCreate(Bundle savedInstance) { 
     ((App) getApplication()).getOneComponent().inject(this); 
     ((App) getApplication()).getSecondComponent().inject(this); 
    } 
} 

私は2つの独立したモジュールを持っており、動作させることはできません。私はエラーを得た:

Error:(16, 10) error: com.test.dagger.module.TwoModule.Two cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. com.test.activity.MoreActivity.two [injected field of type: com.test.dagger.module.TwoModule.Two two]

Error:(16, 10) error: com.test.dagger.module.OneModule.One cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method. com.test.activity.MoreActivity.one [injected field of type: com.test.dagger.module.OneModule.One one]

public class MoreActivity extends SingleFragmentActivity { 

    @Inject OneModule.One one; 
    @Inject TwoModule.Two two; 

    @Override 
    protected Fragment createFragment() { 

     ((App)getApplication()).getOneComponent().inject(this); 
     ((App)getApplication()).getTwoComponent().inject(this); 

     return SimpleFragment.newInstance(MoreActivity.class.getSimpleName()); 
    } 
} 

@Module 
public class OneModule { 
    public class One { 

    } 

    @Provides 
    @Singleton 
    One provideOne() { 
     return new One(); 
    } 
} 

@Module 
public class TwoModule { 

    public class Two { 

    } 

    @Provides 
    @Singleton 
    Two provideTwo() { 
     return new Two(); 
    } 
} 

@Singleton 
@Component(modules = OneModule.class) 
public interface OneComponent { 
    void inject(MoreActivity activity); 
} 

@Singleton 
@Component(modules = TwoModule.class) 
public interface TwoComponent { 
    void inject(MoreActivity activity); 
} 

答えて

1

いいえ、フィールドインジェクションを使用するように、あなたのコンポーネントが@Injectでマークされた依存関係のすべてを提供できるようにする必要があります。

クラスごとに複数のコンポーネントを使用する場合は、プロビジョニングメソッドを使用してフィールドを手動で設定できます。

​​

そして

public class MoreActivity extends SingleFragmentActivity { 

    OneModule.One one; 
    TwoModule.Two two; 

    @Override 
    protected Fragment createFragment() { 

     one = ((App)getApplication()).getOneComponent().one(); 
     two = ((App)getApplication()).getTwoComponent().two(); 

     return SimpleFragment.newInstance(MoreActivity.class.getSimpleName()); 
    } 
} 
+1

それは(なし@Inject注釈...)奇妙に見えますが、動作します。あなたは私の例のようにクラスごとに複数のコンポーネントを使用しないでください。これは問題ありませんか? – marioosh

+0

個人的に、私は1つの '@Singleton'コンポーネントを使用し、すべての' @ Module'をそのコンポーネントにバインドします。私はそれを 'ApplicationComponent'と呼ぶ傾向があります。 – EpicPandaForce

+0

ドキュメントの参照情報と、複数の場所に1つのタイプを注入できない理由を説明してください。 –

関連する問題