Dagger 2 error: cannot be provided without an @Inject constructor

Dagger 2 error: cannot be provided without an @Inject constructor or from an @Provides-annotated method

Make sure the scope is different between the component and its subcomponent, or component and it’s parent component that’s declared using the dependencies.

Make sure the parent component expose the objects that you will be using in the component. In this depencencies example below, AppPref exposeAppPref(); is exposing the AppPref to it’s child components. The method name doesn’t matter, but the type of method has to be the type of the object you want to make it available to child components.
The component AppComponent.java

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    AppPref exposeAppPref(); //make sure this is there
}

The child component ActivityComponent.java depending on the parent component AppComponent.java

@UserScope
@Component (dependencies = {AppComponent.class})
public interface ActivityComponent {
    void inject(MainActivity activity);
}

In this subcomponent example below, AppPref createAppPref(AppPrefModule appPrefModule); exposing the AppPref to its child components.
The component AppComponent.java

@Singleton
@Component(modules = {AppModule.class})
public interface AppComponent {
    AppPref createAppPref(AppPrefModule appPrefModule); //make sure this is there
}

The child component ActivityComponent.java depending on the parent component AppComponent.java

@UserScope
@Subcomponent (module = {AppPrefModule.class})
public interface ActivityComponent {
    void inject(MainActivity activity);
}

With multiple layers of parents, for example, grandparent, parent and child, and there is an object called AppPref, the grandparent has to expose AppPref so it is available for the parent, and the parent also has to expose this AppPref so the child can access it.

Make sure you have the provider methods in the module with the @provider annotation for the objects you want to inject or pass into the provider method as parameters in other modules within the same scope.

//When injecting the appPref
@Inject AppPref appPref;


//The Application is provided in the ApplicationModule
@Singleton
@Provides
Application providesApplication() {
    return sApplication;
}


//The Application argument is available here because it is provided in the ApplicationModule, and this AppPrefModule is either the child component of the App Component that contains the ApplicationModule or in the same scope of App Component.
@ApplicationScope
@Provides
public AppPref provideSharedPreferences(Application application) {
    return new AppPref(application);
}

Search within Codexpedia

Custom Search

Search the entire web

Custom Search