pstobiecki
pstobiecki

Reputation: 1874

Dagger 2.10: Subcomponent + Custom scope = "cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method"

Why does the below code fail to compile with the following error, and what should be done to fix it?

Error:(9, 8) error: [SubComponent.inject(MainActivity)] java.lang.Integer cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
java.lang.Integer is injected at
MainActivity.abc
MainActivity is injected at
SubComponent.inject(activity)

TL;DR: I am trying to create a subcomponent with a different scope than the parent component, and inject a dependency from the subcomponent into an activity.


App.java

public class App extends Application {
    private AppComponent appComponent;

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent = DaggerAppComponent.create();
        appComponent.inject(this);
        if (BuildConfig.DEBUG) {
            Timber.plant(new Timber.DebugTree());
        }
    }

    public AppComponent getAppComponent() {
        return appComponent;
    }

    public static App app(Context context) {
        return (App) context.getApplicationContext();
    }
}

AppComponent.java

@Singleton
@Component
public interface AppComponent {
    void inject(App app);

    SubComponent.Builder subComponent();
}

MainActivity.java

public class MainActivity extends AppCompatActivity {
    @Inject
    int abc;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        App.app(this).getAppComponent()
                .subComponent()
                .userModule(new SubModule())
                .build()
                .inject(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
    }
}

SubComponent.java

@SubScope
@Subcomponent(modules = {SubModule.class})
public interface SubComponent {
    void inject(MainActivity activity);

    @Subcomponent.Builder
    interface Builder {
        Builder userModule(SubModule module);

        SubComponent build();
    }
}

SubModule.java

@Module
public class SubModule {
    @Provides
    @SubScope
    public int provideAbc() {
        return 1;
    }
}

SubScope.java

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
public @interface SubScope {
}

Upvotes: 1

Views: 615

Answers (1)

pstobiecki
pstobiecki

Reputation: 1874

To make it work, I just had to change @Qualifier to @Scope in SubScope:

@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface SubScope {
}

Upvotes: 3

Related Questions