Using Dagger 2, is it correct to inject an Activity into its local Component?

Viewed 602

I have a Component which regroups the current Activity and its Fragments as I want the scope to be for this Activity only and not for the entire application. So in the onCreate method of this activity, I create my Component and I inject the current Activity into it (see code below).

I'd like to know if what I'm doing is correct or if there is a better way to do that?

FYI, I'm following the MVP design pattern.

Component

@Singleton
@Component(modules = {
        FragmentX1Module.class,
        FragmentX2Module.class,
        ActivityXModule.class,
        RepositoryModule.class,
})
public interface ActivityXComponent {
    void inject(FragmentX1Module fragment);

    void inject(FragmentX2Module fragment);

    void inject(ActivityXModule activity);
}

Activity

private ActivityXComponent mXComponent;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_x);

    mXComponent = DaggerActivityXComponent.builder()
            .activityXModule(new ActivityXModule(this)) // I need the Activity Context for later uses
            .build();

    mXComponent.inject(this);

    // ...
}
1 Answers
Related