Android上的Dagger 2多次注入

时间:2016-04-04 15:54:18

标签: android dagger

我有2次注射的活动。每个注入的组件单独工作,但注入两个组件会导致以下错误:

Error:(12, 10) error: android.app.Fragment cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
fr.daggertest.MainActivity.fragmentB
[injected field of type: android.app.Fragment fragmentB]

Error:(12, 10) error: android.app.Application cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
fr.daggertest.MainActivity.applicationA
[injected field of type: android.app.Application applicationA]

但是他们都已经注释了@Provides,所以我不知道错误是什么?

MainActivity.java

public class MainActivity extends AppCompatActivity {

@Inject
Fragment fragmentB;

@Inject
Application applicationA;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // create component & inject...
}

模块&组件:

@Component(modules={ModuleA.class})
@Singleton
public interface ComponentA {
    void inject(MainActivity activity);
}

@Component(modules={ModuleB.class})
@Singleton
public interface ComponentB {
    void inject(MainActivity activity);
}

@Module
public class ModuleA {
    Application mApplication;

    public ModuleA(Application application) {
        mApplication = application;
    }

    @Provides
    public Application provideApplication() {
        return mApplication;
    }
}

@Module
public class ModuleB {
     Fragment mFragment;

    public ModuleB(Fragment fragment) {
        mFragment = fragment;
    }

    @Provides
    public Fragment provideFragment() {
        return mFragment;
    }
}

1 个答案:

答案 0 :(得分:1)

If you try to inject an Activity with a Component Dagger 2 will check that Component can provide every dependency annotated with @Inject

Right now your Components (probably) only provides one of two dependencies. Make one component depend on the other one or make one of them take both Modules

Another possible solution could be change your Components to this:

@Singleton
public interface ComponentA {
    Application getApplication();
}

@Component(modules={ModuleB.class})
@Singleton
public interface ComponentB {
    Fragment getFragment();
}

and change your injecting code to this:

ComponentA componentA = ...
ComponentB componentB = ...
applicationA = componentA.getApplication();
fragmentB = componentB.getFragment();