Проблема с введением зависимости во фрагмент кинжала - PullRequest
0 голосов
/ 17 декабря 2018

В настоящее время я работаю над приложением для Android и использую кинжал для внедрения зависимостей.У меня возникли проблемы при попытке ввести зависимости в фрагменты.Я использую сервис для Bluetooth, который я предоставляю в следующем модуле.

@Module
public abstract class BluetoothModule {

    @Provides
    @Singleton
    @NonNull
    static RxBleClient provideRxBleClient(Context context) {
        RxBleClient client = RxBleClient.create(context);

        RxBleClient.setLogLevel(RxBleLog.VERBOSE);
        return client;
    }

    @Binds
    @Reusable
    @Production
    abstract IBluetoothService provideBlueToothService(BluetoothService bluetoothService);

    @Binds
    @Reusable
    @Test
    abstract IBluetoothService provideMockBlueToothService(MockBluetoothService bluetoothService);

}

Поскольку я использую шаблон MVP, я хотел внедрить этот сервис в презентатор (внедрение конструктора), а затем презентатор во фрагмент (используя полеинъекции).Все работает хорошо, если я внедряю докладчика в основную деятельность.

@Module
public abstract class MainActivityModule {

    @Provides
    @ActivityScoped
    static MainActivityPresenter provideMainActivityPresenter(
            SchedulerProvider schedulerProvider,
            @Test IBluetoothService bluetoothService) {

        return new MainActivityPresenter(schedulerProvider, bluetoothService);
    }


}

Однако, когда я внедряю BluetoothService int FragmentPresenter

@Module
public abstract class MapFragmentModule {

    @Provides
    @Reusable
    static MapPresenter provideMapPresenter(SchedulerProvider provider,
                                            @Test IBluetoothService bluetoothService) {
        return new MapPresenter(provider,bluetoothService);
    }
}

У меня появляется ошибка

error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] com.wavy.services.bluetooth.IBluetoothService cannot be provided without an @Provides-annotated method.
public interface ApplicationComponent extends AndroidInjector<DaggerApplication>{
       ^
      com.wavy.services.bluetooth.IBluetoothService is injected at
          com.wavy.ui.map.MapPresenter.<init>(…, bluetoothService)
      com.wavy.ui.map.MapPresenter is injected at
          com.wavy.ui.map.MapFragment.mapPresenter
      com.wavy.ui.map.MapFragment is injected at
          com.wavy.ui.MainActivity.mapFragment
      com.wavy.ui.MainActivity is injected at
          dagger.android.AndroidInjector.inject(T)
  component path: com.wavy.config.dagger.components.ApplicationComponent → com.wavy.config.dagger.builders.ActivityBuilder_BindMainActivity.MainActivitySubcomponent

Так что я нашел эту проблему на github с такой же проблемой, как у меня Issue Link

Решением было не использовать аннотацию @Inject в конструкторе Fragment, поэтому я сделал это, и после этого я получил еще одну ошибку

error: [Dagger/MissingBinding] [dagger.android.AndroidInjector.inject(T)] com.wavy.ui.map.MapFragment cannot be provided without an @Inject constructor or an @Provides-annotated method. This type supports members injection but cannot be implicitly provided.
public interface ApplicationComponent extends AndroidInjector<DaggerApplication>{
       ^
  A binding with matching key exists in component: com.wavy.config.dagger.builders.FragmentBuilder_BindMapFragment.MapFragmentSubcomponent
      com.wavy.ui.map.MapFragment is injected at
          com.wavy.ui.MainActivity.mapFragment
      com.wavy.ui.MainActivity is injected at
          dagger.android.AndroidInjector.inject(T)
  component path: com.wavy.config.dagger.components.ApplicationComponent → com.wavy.config.dagger.builders.ActivityBuilder_BindMainActivity.MainActivitySubcomponent

Так я предоставляю свой фрагмент

  @ContributesAndroidInjector(modules = {MapFragmentModule.class})
  abstract MapFragment bindMapFragment();

Служба Bluetooth

public class BluetoothService implements IBluetoothService {
        private final RxBleClient rxBleClient;

        @Inject
        public BluetoothService(RxBleClient rxBleClient) {
            this.rxBleClient = rxBleClient;
        }

//code omitted for clarity
}

Фрагмент карты

public class MapFragment extends BaseFragment {

    @Inject
    MapPresenter mapPresenter;

    @Inject
    public MapFragment() {
        // Required empty public constructor
    }
//code omitted for clarty
}

Представитель карты

public class MapPresenter extends BasePresenter<MapFragment> {
    private final IBluetoothService bluetoothService;

    @Inject
    public MapPresenter(SchedulerProvider schedulerProvider,
                        IBluetoothService bluetoothService) {
        super(schedulerProvider);
        this.bluetoothService = bluetoothService;
    }
    //code ommited for clarity
}

ActivityBuilder

@Module
public abstract class ActivityBuilder {

    @ActivityScoped
    @ContributesAndroidInjector(modules = {MainActivityModule.class, FragmentBuilder.class})
    abstract MainActivity bindMainActivity();

}

AppComponent

@Singleton
@Component(modules = {
        AndroidSupportInjectionModule.class,
        ApplicationModule.class,
        ActivityBuilder.class,
        BluetoothModule.class,
        RetrofitRestClientModule.class,
        RxModule.class,
        ApiModule.class,
        RoomDatabaseModule.class
})
public interface ApplicationComponent extends AndroidInjector<DaggerApplication>{

    void inject(WavyApplication application);

    @Override
    void inject(DaggerApplication instance);

    @Component.Builder
    interface Builder{
        @BindsInstance
        Builder application(Application application);
        ApplicationComponent build();

    }
}

Буду очень признателен за любые идеи, как решить эту проблему, спасибо за помощь

1 Ответ

0 голосов
/ 17 декабря 2018

Вы, вероятно, забыли включить модуль фрагментов в свой подкомпонент активности.У вас должно быть что-то вроде этого:

abstract class MapFragmentBuilderModule {

    @ContributesAndroidInjector(modules = {MapFragmentModule.class})
    abstract MapFragment bindMapFragment();

}

и затем в вашем модуле активности:

@ActivityScoped
@ContributesAndroidInjector(modules = [MainModule::class, MapFragmentBuilderModule::class])
internal abstract fun mainActivity(): MainActivity
...