android - Dagger & nested injections -


i'm using dagger inject dependencies android application, , stumbled on issue not entirely sure how resolve in clean way.

what i'm trying achieve instanciate helpers , inject them within activity, , have these helpers contain injected members too.

what works

the activity helper being injected:

public class myactivity extends activity {     @inject samplehelper helper;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);          ((myapplication) getapplication()).inject(this);          log.i("debug", "helper = " + helper);         log.i("debug", "helper context = " + helper.context);     } } 

the application creating object graph:

public class myapplication extends application {     private objectgraph graph;      @override     public void oncreate() {         super.oncreate();          graph = objectgraph.create(getmodules());     }      private object[] getmodules() {         return new object[] { new mymodule(this) };     }      public void inject(object target) {         graph.inject(target);     } } 

the injection works when instanciate directly samplehelper class, in turn receives injected application context:

@singleton public class samplehelper {      @inject public context context;      @inject     public samplehelper() {} } 

with following module:

@module(     injects = { myactivity.class },     complete = false,     library = true ) public class mymodule {     private final myapplication application;      public mymodule(myapplication application) {       this.application = application;     }      @provides @singleton context provideapplicationcontext() {         return application;     } } 

what doesn't work

however, when separate helper interface implementation:

public interface samplehelper { }  @singleton public class samplehelperimpl implements samplehelper {      @inject public context context;      @inject     public samplehelperimpl() {} } 

and add dagger module:

public class mymodule {     ...      // added method     @provides @singleton public samplehelper providesamplehelper() {         return new samplehelperimpl();     }      ... } 

the context doesn't injected in samplehelperimpl, have expected. now, guess due samplehelperimpl being instanciated through direct constructor call rather injection-initiated constructor call, because mymodule#provideapplicationcontext() doesn't called, guess i'm missing dagger (which likely, previous di experiences included spring).

any idea how have context injected in injected helper implementation, in "clean dagger" way?

thanks lot!

this old question think want this:

@provides @singleton public samplehelper providesamplehelper(samplehelperimpl impl) {     return impl; } 

this way dagger create samplehelperimpl , therefore inject it.


Comments