Dagger - Inject provide beans both to field variable and constructor at same this

StackOverflow https://stackoverflow.com/questions/23175616

  •  06-07-2023
  •  | 
  •  

سؤال

I have a class with the following structure.

Is it "legal" in Dagger to @Inject beans in field variables and constructors at the same time, as I have done below? If no - I have a MyActivityModule and MyApplicationModule, how can I get the dependencies from MyApplicationModule and add them to the constructor I use in the provideWhatEvery in the MyActivityModule ?

@Inject SmsFormatter mSmsFormatter;
@Inject SmsGuardiansUtils smsGuardiansUtils;
@Inject BipperMediaPlayer bipperMediaPlayer;
@Inject MixPanelUtils mMixpanelUtils;


@Inject
public ImHereController(View view, Context context, AlarmModel alarmModel, ActionBarListener actionBarListener,
        FragmentController fragmentController){
    super(view, context, alarmModel, actionBarListener, fragmentController);
}
هل كانت مفيدة؟

المحلول

You can inject fields and constructors as you have. The constructor parameters will be resolved first and injected upon construction, and after that the fields will be injected.

The other parts of your question are unclear - it doesn't matter whether you add dependencies by field injection or constructor injection - if you wanted to add them all with constructor injection you could.

The only time you must use field injection is where you have an object whose instantiation you cannot control, and therefore dagger cannot itself instantiate (like Activity and Application subtypes.)

All that said, I would not use both without some compelling reason - constructor injection is more semantically clear and you can make the instance variables final. Alternately, field injection is more terse, and possibly more readable in cases. I would pick one, and not both.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top