Eselfar
Eselfar

Reputation: 3869

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

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);

    // ...
}

Upvotes: 3

Views: 617

Answers (1)

gjsalot
gjsalot

Reputation: 768

I would assume there are objects you would want to inject in multiple activities, perhaps from your RepositoryModule. Thus I would suggest you have an app wide component such as:

@Singleton
@Component(modules = {
        RepositoryModule.class,
})
public interface AppComponent {
    ActivityXComponent plus(ActivityXModule module);
}

Then you should scope your ActivityXComponent as something like @PerActivity.

Take a look at http://frogermcs.github.io/dependency-injection-with-dagger-2-custom-scopes/ for a good example.

Upvotes: 2

Related Questions