简体   繁体   中英

Dagger2 - Module must be set

I have Application component with two modules - applicationModule and activityModule. In my MvpApp.java class i create component with modules:

public class MvpApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        mApplicationComponent = DaggerApplicationComponent.builder()
                .activityModule(new ActivityModule())
                .applicationModule(new ApplicationModule(this))
                .build();
    }
}

My ApplicationModule has constructor with Application and i send it. But my `Activity module has constructor:

    public ActivityModule(AppCompatActivity activity) {
        this.mActivity = activity;
    }

And how can i send my MainActivity instance into this constructor? When i try

        mApplicationComponent = DaggerApplicationComponent.builder()
                .activityModule(new ActivityModule(new MainActivity()))
                .applicationModule(new ApplicationModule(this))
                .build();

I get an error.

First of all, it is not recommended to provide context to the dagger graph via module constructor. You should use the @BindsInstance annotation in your dagger component builder.

Also, you can not create a module with the constructor param of activity. You probably want to inject some object into your MainActivity . In this case, you need to create a method in your dagger component with a similar declaration and call it in your activity before calling

ApplicationComponent

public interface ApplicationComponent {
    // your previous code

    void inject(MainActivity target);
}

MainActivity

@Inject SomeClass someClass; // <- some class you want to inject from graph

@Override
protected void onCreate(Bundle savedInstanceState) {
    ((MvpApp) getApplicationContext()).mApplicationComponent.inject(this);
    super.onCreate(savedInstanceState);
    // your code
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM