java - Dagger2 where inject @Named @Provides in dependent module? -
i use dagger2 demo https://guides.codepath.com/android/dependency-injection-with-dagger-2. want use cached , non_cached retrofit call. create in netmodule.java
@provides @named("cached") @singleton okhttpclient provideokhttpclient(cache cache) { okhttpclient okhttpclient = new okhttpclient.builder() .cache(cache) .build(); return okhttpclient; } @provides @named("non_cached") @singleton okhttpclient provideokhttpclientnoncached() { okhttpclient okhttpclient = new okhttpclient.builder() .build(); return okhttpclient; }
githubmodule.java dependent on netmodule.java. githubcomponent.java
@userscope @component(dependencies = netcomponent.class, modules = githubmodule.class) public interface githubcomponent { void inject(demodaggeractivity activity); }
my netcomponent.java
@singleton @component(modules={applicationmodule.class, netmodule.class}) public interface netcomponent { // downstream components need these exposed retrofit retrofit(); okhttpclient okhttpclient(); sharedpreferences sharedpreferences(); }
in demodaggeractivity.java
inject retrofit:
@inject @named("cached") okhttpclient mokhttpclient; @inject retrofit mretrofit;
after rebuild project error:
where can tell dagger, want use cached or non_cached retrofit?
your retrofit provider should use @named
annotation okhttpclient, example:
@provides @singleton public retrofit provideretrofit(@named("cached") okhttpclient okhttpclient) { return new retrofit.builder() .baseurl("...") .addconverterfactory(gsonconverterfactory.create()) .client(okhttpclient) .build(); }
Comments
Post a Comment