1

For example, Let say like below.

  • there is a Activity named MyActivity.
  • there are two class named A, B and MyActivity has these class instances.
  • there is a class named C that I want to inject into A & B.
  • C has a scope that follows activity lifecycle.

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

J.ty
  • 337
  • 1
  • 3
  • 18

1 Answers1

4

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);
    }
}
David Rawson
  • 20,912
  • 7
  • 88
  • 124