J.ty
J.ty

Reputation: 347

How can I inject different instance with Dagger2

For example, Let say like below.

In this situation, regardless of the scope, Is there any way of passing a different instance of C into A, B with Dagger 2?

Upvotes: 1

Views: 1038

Answers (1)

David Rawson
David Rawson

Reputation: 21497

You need to use qualifiers. From the qualifiers section of the dagger user's guide:

Sometimes the type alone is insufficient to identify a dependency. In this case, we add a qualifier annotation.

For your case, mere C is not enough to identify the two different dependencies you want injected into A and B. So you would add a qualifier to distinguish the two instances. Here is an example:

public class A {

    private final C c;

    @Inject
    public A(@Named("Instance 1") C c) {
        this.c = c;
    }
}

public class B {
    private final C c;

    @Inject 
    public B(@Named("Instance 2") C c) {
        this.c = c;
    }
}

Module:

@Module
public class CModule() {

    @Provides
    @Named("Instance 1")
    C provideInstance1OfC() {
        return new C();
    }

    @Provides
    @Named("Instance 2")
    C provideInstance2OfC() {
        return new C();
    }
}

Component:

@Component( modules = { CModule.class } )
public interface ActivityComponent {
    void inject(MyActivitiy activity);
}

Then finally:

public class MyActivity extends Activity {
    @Inject A a;
    @Inject B b;

    @Override
    void onCreate() {
         super.onCreate();
         DaggerActivityComponent.builder()
             .cModule(new CModule())
             .build()
             .inject(this);
    }
}

Upvotes: 4

Related Questions