android - How to inject same Dagger 2 dependency with different implementations based on the Context? -


i have dagger 2 dependency provided differently if it’s activity or other context instance (e.g., service). both refer same interface implementation varies. how organise using dagger 2?

right now, i’m trying 2 different components, activitycomponent , contextcomponent respective modules follows:

@activityscope         @subcomponent(               modules = {                     activitymodule.class,                     contextmodule.class   })         public interface activitycomponent { }  @module     public class activitymodule {      @provides     @myactivityqualifier     public myobject providemyobject() {     } }   @contextscope @subcomponent(           modules = {     contextmodule.class   })     public interface contextcomponent {    }  @module public class contextmodule.class {      @provides     public myobject providemyobject() {     } }  

then, if i’m using myobject in activity, have add qualifier follows:

@inject @myactivityqualifier myobject myobject;  

this feels wrong i’m not sure why. there better way?

you using subcomponents.
question is: can or should both objects "visible" (usable, injectable, ...) @ same time?

  • yes: will have use sort of qualifier. or else can't distinguish them.
  • no: can "hide" them not exposing dependency dependent component. have use normal component instead of @subcomponent in case, , don't add getmyinterface() method parent component.

and there aren't other options, because have 2 components dependent on each other. approach looks fine information provide.

note can qualify one of implementations. in project, use qualified @named("public") annotation common implementation without user data. if don't add qualifier other 1 (unqualified).


with independent components, e.g. activityacomponent , activitybcomponent switch implementation gets provided using different modules.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -