Dagger can not provide my dependencies - java

I'm having a problem with Dagger 2.
I want a general NetworkModule where I can share my retrofit, etc.. and then later on I want subcomponents so that per flow I have different Retrofit Interfaces for example login, ...
My setup right now is:
#Module
public class NetworkModule {
#Provides
#Singleton
#Named("Default")
Retrofit provideRetrofit() {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("myUrl")
.build();
return retrofit;
}
}
I also have a ApplicationModule ( I don't know if this is the correct way to have a ApplicationModule ).
#Module
public class ApplicationModule {
private Application application;
public ApplicationModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return this.application;
}
}
And last but not least my Component that binds the two together:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetworkComponent {
Retrofit provideRetrofit();
void inject(MainActivity activity);
}
Now I don't see the problem but when I do:
((MyApplication) getApplication()).getNetworkComponent().inject(this);
Where this is created as:
DaggerNetworkComponent.builder().applicationModule(new ApplicationModule(this)).build();
I can't compile and I get the error:
retrofit2.Retrofit cannot be provided without an #Inject constructor or from an #Provides- or #Produces-annotated method.

Add #Named("Default") to your Retrofit provideRetrofit(); in NetworkComponent

You can refer to the following classes for the usage of dagger 2 and retrofit :
Injector.java
public class Injector {
// Singleton instance
private static Injector instance;
// components
private AppComponent appComponent;
// Private constructor to make it singleton
private Injector() {
}
/**
* Get the singleton Injector instance
*
* #return Injector
*/
private static Injector instance() {
if (instance == null) {
instance = new Injector();
}
return instance;
}
/**
* Creates application component which used of injection later.
*
* #param application
*/
public static void createApplicationComponent(Application application) {
if (instance().appComponent == null) {
instance().appComponent = DaggerAppComponent.builder()
.appModule(new AppModule(application))
.build();
}
}
/**
* Returns the component for injection.
*
* #return
*/
public static AppComponent component() {
return instance().appComponent;
}
}
AppComponent.java
#Singleton
#Component(modules = {
AppModule.class,
ApiModule.class,
})
public interface AppComponent {
// Other utility classes for injection
}
ApiModule.java which similar to your network module class
#Module
public class ApiModule {
#Provides
#Singleton
public Retrofit provideApi(
OkHttpClient client,
Converter.Factory converterFactory,
CallAdapter.Factory callAdapterFactory) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Config.API_BASE_URL)
.client(client)
.addConverterFactory(converterFactory)
.addCallAdapterFactory(callAdapterFactory)
.build();
return retrofit;
}
}
AppModule.java
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Provides
#Singleton
public Application provideApplication() {
return application;
}
#Provides
#Singleton
public Context provideContext() {
return application;
}
}
later in your activity class you can use Injector.component().inject(this); to inject dagger 2 dependencies
For more clarification you can refer this github repo

Related

Dagger2 - cannot be provided without an #Inject constructor or from an #Provides-annotated method

I I am using Android Dagger2 but I am getting the error like it
error: [dagger.android.AndroidInjector.inject(T)] android.app.Application cannot be provided without an #Inject constructor or from an #Provides-annotated method.
android.app.Application is injected at
com.nwrn.pfdy.DI.Module.AppModule.provideContext(application)
android.content.Context is injected at
com.nwrn.pfdy.DI.Module.AppModule.provideAppPreferencesHelper(context)
com.nwrn.pfdy.Data.Prefs.AppPreferencesHelper is injected at
com.nwrn.pfdy.DI.Module.NetworkModule.provideAddCookiesInterceptor(appPreferencesHelper)
com.nwrn.pfdy.Network.Cookies.AddCookiesInterceptor is injected at
com.nwrn.pfdy.DI.Module.NetworkModule.provideRetrofitService(addCookiesInterceptor, …)
com.nwrn.pfdy.Network.Retrofit.RetrofitService is injected at
com.nwrn.pfdy.View.Login.LoginActivityModule.provideLoginViewModel(retrofitService)
com.nwrn.pfdy.View.Login.LoginViewModel is injected at
com.nwrn.pfdy.View.Login.LoginActivity.mLoginViewModel
com.nwrn.pfdy.View.Login.LoginActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
This is my AppComponent Code
#Singleton
#Component(modules = {AndroidInjectionModule.class, AppModule.class, ActivityModule.class, NetworkModule.class})
public interface AppComponent {
void inject(BaseApplication baseApplication);
#Component.Builder
interface Builder{
#BindsInstance
Builder application(BaseApplication baseApplication);
AppComponent build();
}
}
Below is My Code of Modules
#Module
public class AppModule {
#Provides
#Singleton
Context provideContext(Application application) {
return application;
}
#Provides
#Singleton
AppPreferencesHelper provideAppPreferencesHelper(Context context) {
return new AppPreferencesHelper(context);
}
}
this is another module
#Module
public class NetworkModule {
#Provides
AddCookiesInterceptor provideAddCookiesInterceptor(AppPreferencesHelper appPreferencesHelper) {
return new AddCookiesInterceptor(appPreferencesHelper);
}
#Provides
ReceivedCookiesInterceptor provideReceivedCookiesInterceptor(AppPreferencesHelper appPreferencesHelper) {
return new ReceivedCookiesInterceptor(appPreferencesHelper);
}
#Singleton
#Provides
RetrofitService provideRetrofitService(AddCookiesInterceptor addCookiesInterceptor, ReceivedCookiesInterceptor receivedCookiesInterceptor) {
return new RetrofitClient(addCookiesInterceptor, receivedCookiesInterceptor).getService();
}
}
Below code is About Injection Class
public class RetrofitClient {
private RetrofitService service;
private static final String baseURL = "http://192.168.0.33:8070/";
public RetrofitClient(AddCookiesInterceptor addCookiesInterceptor, ReceivedCookiesInterceptor receivedCookiesInterceptor) {
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS)
.writeTimeout(20, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
client.interceptors().add(addCookiesInterceptor);
client.interceptors().add(receivedCookiesInterceptor);
Retrofit retrofit = new Retrofit.Builder().baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
service = retrofit.create(RetrofitService.class);
}
public RetrofitService getService() {
return service;
}
}
public class AddCookiesInterceptor implements Interceptor {
private AppPreferencesHelper mAppPreferencesHelper;
public AddCookiesInterceptor(AppPreferencesHelper appPreferencesHelper){
this.mAppPreferencesHelper = appPreferencesHelper;
}
#Override
public Response intercept(Chain chain) throws IOException {
Request.Builder builder = chain.request().newBuilder();
Set<String> preferences = mAppPreferencesHelper.getCookie();
for (String cookie : preferences) {
builder.addHeader("Cookie", cookie);
}
// Web,Android,iOS 구분을 위해 User-Agent 세팅
builder.removeHeader("User-Agent").addHeader("User-Agent", "Android");
return chain.proceed(builder.build());
}
}
public class ReceivedCookiesInterceptor implements Interceptor {
private AppPreferencesHelper mAppPreferencesHelper;
public ReceivedCookiesInterceptor(AppPreferencesHelper appPreferencesHelper)
{
this.mAppPreferencesHelper = appPreferencesHelper;
}
#Override
public Response intercept(Chain chain) throws IOException {
Response originalResponse = chain.proceed(chain.request());
if (!originalResponse.headers("Set-Cookie").isEmpty()) {
HashSet<String> cookies = new HashSet<>(originalResponse.headers("Set-Cookie"));
// Preference에 cookies를 넣어주는 작업을 수행
mAppPreferencesHelper.setCookie(cookies);
}
return originalResponse;
}
}
public class AppPreferencesHelper implements PreferencesHelper {
private static final String PREF_KEY_COOKIE_NAME = "PREF_KEY_COOKIE_NAME";
private final SharedPreferences mPrefs;
public AppPreferencesHelper(Context context) {
mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
}
#Override
public Set<String> getCookie() {
return mPrefs.getStringSet(PREF_KEY_COOKIE_NAME, new HashSet<String>());
}
#Override
public void setCookie(HashSet<String> cookie) {
mPrefs.edit().putStringSet(PREF_KEY_COOKIE_NAME, cookie);
}
}
public interface PreferencesHelper {
Set<String> getCookie();
void setCookie(HashSet<String> cookie);
}
Injection Flow is like this
Rerofit2 => AddCookiesInterceptor, ReceivedCookiesInterceptr => AppPreferencesHelper => Context
what i got about this error by testing is that error is caused by provideContext in AppModule.
if i change AppPreferencesHelper Constructor without parameter like this (without provideContext) it doesn't make an error
public AppConstructor(){
}
and
#Module
public class AppModule {
#Provides
#Singleton
Context provideContext(Application application) {
return application;
}
#Provides
#Singleton
AppPreferencesHelper provideAppPreferencesHelper() {
return new AppPreferencesHelper();
}
}
Many thanks for any suggestions
Edited
Seems like you need to change Application to BaseApplication at provideContext method.
Hope this helps!

Inject presenter into activity via Dagger

I want to know how to inject Presenter in activity using code Following are details
Following is error message:
Error:(12, 46) error: cannot find symbol class DaggerCategoryPresenterComponent
Error:(9, 46) error: cannot find symbol class DaggerNetComponent
Error:(18, 10) error: [Dagger/MissingBinding] com.headytest.android.category_listing.CategoryContract.CategoryPresenter cannot be provided without an #Provides-annotated method.
com.headytest.android.category_listing.CategoryContract.CategoryPresenter is injected at
com.headytest.android.MainActivity.categoryPresenter
com.headytest.android.MainActivity is injected at
com.headytest.android.dagger_component.NetComponent.inject(com.headytest.android.MainActivity)
Following are modules
#Module
public class NetworkModule {
String baseURL;
public NetworkModule(String baseURL) {
this.baseURL = baseURL;
}
#Provides
#Singleton
Cache provideHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024;
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkhttpClient(Cache cache) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder client = new OkHttpClient.Builder();
client.cache(cache);
client.addInterceptor(interceptor);
return client.build();
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
try {
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(baseURL)
.client(okHttpClient)
.build();
} catch (Exception e) {
e.printStackTrace();
return new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.baseUrl(Constants.BASE_URL)
.client(okHttpClient)
.build();
}
}
}
ApplicationModule
#Module
public class ApplicationModule {
Application application;
public ApplicationModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return application;
}
}
CategoryContractModule
#Module
public class CategoryContractModule {
public CategoryContractModule() {
}
#Provides
#AScope
CategoryContract.CategoryPresenter providesCategoryPresenter(CategoryPresenterImpl categoryPresenter) {
return (CategoryContract.CategoryPresenter)categoryPresenter;
}
}
Following are components:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
void inject(MainActivity activity);
}
CategoryPresenterComponent:
#AScope
#Component(dependencies = NetComponent.class, modules =
{CategoryContractModule.class})
public interface CategoryPresenterComponent {
void inject(MainActivity activity);
}
AScope
#Scope
#Retention(RetentionPolicy.RUNTIME)
public #interface AScope {
}
Following is the code in MainActivity:
#Inject
CategoryPresenter categoryPresenter;
#Inject
Retrofit retrofit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerCategoryPresenterComponent.builder()
.categoryContractModule(new CategoryContractModule())
.netComponent(((App) getApplicationContext()).getNetComponent())
.build()
.inject(this);
}
CategoryPresenterImpl
public class CategoryPresenterImpl implements CategoryContract.CategoryPresenter {
#Inject
public CategoryPresenterImpl() {
}
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void getCategoryLiast() {
}
}
I assume current error will be easy to fix, because it very much looks like this issue.
You've instructed Dagger how to provide #AScope CategoryContract.CategoryPresenter but in activity you request Dagger to inject CategoryContract.CategoryPresenter. Dagger is confused at this point, because those two things do not match.
What you have to do, is simply add #AScope to categoryPresenter:
#Inject
#AScope
CategoryPresenter categoryPresenter;
I've checked out your project. The problem was in NetComponent.java:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
void inject(MainActivity activity);
}
The issue is in line void inject(MainActivity activity). Why is this an issue? Because by the time you construct NetComponent in App, dagger analyzes MainActivity for #Inject annotated field and sees CategoryPresenter. This means, that at this point Dagger should find appropriate provider/binder method in order to be able to inject MainActivity as declared inside this interface.
But it cannot find such a provider/binder method, because it is declared in an another component - CategoryPresenterComponent and this component (NetComponent) is not connected with CategoryPresenterComponent anyhow (subcomponents or component dependencies), thus bindings are not exposed.
Simply removing that line will make your build successful:
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
}
For resolving "Error:cannot access Nullable" refer to this thread, which suggest applying compile 'com.google.code.findbugs:jsr305:3.0.2' to your gradle file.
After doing this you'll overcome that error message and will stumble on retrofit2.Retrofit cannot be provided without an #Inject constructor or an #Provides-annotated method, which has the same symptoms as CategoryPresenter had.
To overcome this issue you have to add a Retrofit provider method inside NetComponent (or to remove #Inject Retrofit retrofit from activity):
#Singleton
#Component(modules = {ApplicationModule.class, NetworkModule.class})
public interface NetComponent {
Retrofit providesRetrofit();
}
After doing this you'll be able to run the app, but you'll end up in a NPE in MainActivity, because of this line:
.categoryContractModule(new CategoryContractModule(retrofit.create(HeadyAPI.class)))
You are referring to retrofit object, which is not yet initialized.
Long story short, your initial question has mutated a couple of times and in fact you had a few problems in your code. Still you have a problem there, because you are trying to use retrofit in order to construct a component, that was supposed to inject the retrofit for you.

Dagger singleton creating new instance every time

I have a module as follows.
#Module
public class AppModule {
private final Application app;
public AppModule(Application app) {
this.app = app;
}
#Provides
#Architecture.ApplicationContext
Context provideContext() {
return app;
}
#Provides //scope is not necessary for parameters stored within the module
public Context context() {
return provideContext();
}
#Singleton
#Provides
Application provideApp() {
return app;
}
#Singleton
#Provides
SoundsRepository provideSoundsRepository(Context context, SoundsDAO soundsDAO) {
return new SoundsRepository(context, soundsDAO);
}
}
A component like this.
#Singleton
#Component(modules = AppModule.class)
public interface AppComponent {
void inject(Global global);
void inject(MainActivity mainActivity);
#Architecture.ApplicationContext
Context getContext();
Application getApplication();
void inject(PostView postView);
void inject(MediaPlayerService mediaPlayerService);
}
In activity, fragment or service, I do this
#Inject
SoundsRepository soundsRepository;
#Override
protected void onCreate(...) {
//....
((Global) getApplication()).getComponent().inject(this);
}
In SoundsRepository
#Singleton
public class SoundsRepository {
#Inject
public SoundsRepository(Context context, SoundsDAO soundsDAO) {
this.context = context;
this.soundsDAO = soundsDAO;
System.out.println(TAG + "INIT");
}
// ....
}
So, now, every time I start to access an activity or service where SoundsRepository is injected, I get a new instance, I mean, the constructor of "SoundsRepository" fires again.
What am I doing wrong?
EDIT : Inject in Application Class
public class Global extends MultiDexApplication {
protected AppComponent appComponent;
private boolean calledAlready = false;
#Override
public void onCreate() {
super.onCreate();
//if (LeakCanary.isInAnalyzerProcess(this)) return;
//LeakCanary.install(this);
initFirebasePersistance();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
appComponent.inject(this);
FrescoUtil.init(getApplicationContext());
}
public AppComponent getComponent() {
return appComponent;
}
}
In your module you have a method that provides an instance of SoundsRepository - good
In your AppComponent you are missing a:
SoundsRepository soundsRepository();
In your Global which extends Application/MultidexApplication you create your DaggerAppComponent - good
In your other activities/fragments/services just call:
Global application = (Global) getApplication();
SoundsRepository sr = application.getComponent().soundsRepository()
Android guarantees you have only one instance of your Application (Global) class for all other actvities/services (its somewhat like a singleton).
So keep your component in that application class, and whenever you need your class, call: (YourApplication) getApplication().getComponent().yourSingleInstanceSomething();
I created and tested sample code for you: https://github.com/zakrzak/StackDaggerTest
Dagger's #Singleton is just a scope, and does not guarantee returning a singular instance of a class.
In my understanding, if you:
void inject(PostView postView);
you tell Dagger to make everything you annotated with #Provided in AppModule accessible in your PostView as soon as you request it with:
#Inject
SoundsRepository soundsRepository;
then dagger just calls the #provided method which in your case returns a new SoundRepository instance:
#Singleton
#Provides
SoundsRepository provideSoundsRepository(Context ........) {
return new SoundsRepository(...);
}
which causes your problem

How to send activity instance to module in a constructor in dagger2

I am using dagger2 in my application. I have created module, component which is being in my entire application so I am initializing it in the application class.
Below is my module, component of dagger2 which are helping for resolving dependencies.
NetComponent.java
#Singleton
#Component(modules = {AppModule.class, NetModule.class})
public interface NetComponent {
void inject(AuthenticationActivity authenticationActivity);
void inject(PaymentActivity paymentActivity);
}
AppModule.java
#Module
public class AppModule {
private Application application;
public AppModule(Application application) {
this.application = application;
}
#Provides
#Singleton
Application providesApplication() {
return application;
}
}
NetModule.java
#Module
public class NetModule {
#Provides
#Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
#Provides
#Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
Cache cache = new Cache(application.getCacheDir(), cacheSize);
return cache;
}
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newBuilder()
//.addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
.cache(cache)
.build();
return okHttpClient;
}
#Provides
#Singleton
#Named("authRetrofit")
Retrofit provideAuthRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(PAYMENT_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
#Provides
#Singleton
#Named("paymentRetrofit")
Retrofit providePaymentRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(LOGIN_SERVICE)
.client(okHttpClient)
.build();
return retrofit;
}
}
AppApplication.java
public class AppApplication extends Application {
private NetComponent mNetComponent;
#Override
public void onCreate() {
super.onCreate();
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.build();
}
public NetComponent getmNetComponent() {
return mNetComponent;
}
}
Validator.java
#Module
public class Validator {
#Provides
com.mobsandgeeks.saripaar.Validator providesValidator(Application application) {
return new com.mobsandgeeks.saripaar.Validator(application);
}
}
I want to pass activity instance to the constructor of Validator in which I am using it.
Suppose I want to inject Validator in MainActivity.java then constructor should have MainActivity instance.
What approach should I take for this ? Should I initialize the dagger dependency in an activity for this and Do I need to create a new component for this ?
You can simply create constructor for your ValidatorModule:
#Module
public class Validator {
private final Activity activity;
public Validator(Activity activity) {
this.activity = activity;
}
#Provides
com.mobsandgeeks.saripaar.Validator providesValidator() {
return new com.mobsandgeeks.saripaar.Validator(activity);
}
}
Let me know if it is what you are looking for

Dagger 2 component dependency not working

The dagger modules
#Module
public class NetModule {
#Provides
#Singleton
Gson provideGson() {
GsonBuilder gsonBuilder = new GsonBuilder();
return gsonBuilder.create();
}
#Provides
#Singleton
OkHttpClient provideOkHttpClient() {
OkHttpClient client = new OkHttpClient();
return client;
}
#Provides
#Singleton
Retrofit provideRetrofit(Gson gson, OkHttpClient okHttpClient) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(BuildConfig.SERVER_BASE_URL)
.client(okHttpClient)
.build();
return retrofit;
}
}
#Module
public class AppModule{
private Application application;
public AppModule(Application application){
this.application = application;
}
#Provides
#Singleton
Application provideApplication() {
return application;
}
}
#Module
public class ImageModule {
#Provides
#Singleton
Picasso providePicasso(Application application, OkHttpClient client) {
Picasso.Builder builder = new Picasso.Builder(application);
builder.downloader(new OkHttp3Downloader(client));
return builder.build();
}
}
These are the components
#Singleton
#Component(modules={NetModule.class})
public interface NetComponent {
void inject(MyFragment fragment);
}
#Singleton
#Component(modules={AppModule.class, ImageModule.class}, dependencies = {NetModule.class})
public interface ImageComponent {
void inject(MyFragment fragment);
}
This is how I am registering the components
public class MyApp extends Application{
#Override
public void onCreate() {
netComponent = DaggerNetComponent.builder()
.netModule(new NetModule())
.build();
imageComponent = DaggerImageComponent.builder()
.appModule(new appModule(this))
.imageModule(new ImageModule())
.build();
}
}
And in the fragment
public class MyFragment extends Fragment {
#Inject
Retrofit retrofit;
#Inject
Picasso picasso;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getNetComponent().inject(this);
((MyApp)getActivity().getApplication()).getImageComponent().inject(this);
....
}
}
I am getting compilation error as below
Error:(25, 10) error: com.squareup.picasso.Picasso cannot be provided
without an #Inject constructor or from an #Provides- or
#Produces-annotated method.
What is the best way to achieve this in dagger 2?
When Component A depends on type B, you're saying that every zero-arg getter on B will be available in A's graph. This means that you don't need to call inject separately on NetComponent, but you do need to expose OkHttpClient in NetComponent's definition.
This means NetComponent would look like this:
#Singleton
#Component(modules={NetModule.class})
public interface NetComponent {
/** Exposes OkHttpClient. Used by components depending on NetComponent. */
OkHttpClient getOkHttpClient();
}
And your onCreateView could look like this:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MyApp)getActivity().getApplication()).getImageComponent().inject(this);
}
Internally, Dagger generates the DaggerNetComponent and DaggerImageComponent in two separate steps, but has ImageComponent call the new getOkHttpClient method. This also means that DaggerImageComponent can accept any implementation of NetComponent, not just the one Dagger generates.
Related resources:
What is the purpose of the non-inject methods in Components in Dagger 2? (see David Rawson's answer)
Dagger 2 subcomponents vs component dependencies
Dagger docs on component dependencies and its link to provision methods

Categories

Resources