Dagger 2: nested dependencies with same arguments in Module

299 Views Asked by At

I have the following classes

    public class X {

    @Inject
    public X(B b){}

    }


    public class A {

    @Inject
    public A(B b){}

    }

    public class B {

    @Inject
    public B(String c){}

    }



    public abstract AppModule {

    @Binds
    abstract A bindA(A a);


    @Binds
    abstract B bindB(B a);

    @Provide
    static String stringForX(){
    return "oneX";
    }

    @Provide
    static String stringForA(){
    return "twoA";
    }

    }

Now B is injected into A and X. But the instance of B to be injected in X and A has to be internally injected with different Strings (stringForX() and stringForA(), respectively) How can i achieve this? I know @Named could be used but i am not sure how exactly in this particular case since B is common amongst them.

Thanks

1

There are 1 best solutions below

1
Saurabh On BEST ANSWER

you have to manually provide 2 instances of B from module using @Named on those(instances of B).

example:

public class X {
  @Inject
   public X(@Named("b1") B b){}

}


public class A {

@Inject
public A(@Named("b2") B b){}

}

public class B {

public B(String c){}

}



public abstract AppModule {

@Binds
abstract A bindA(A a);


@Binds
abstract B bindB(B a);

@Provides()
@Named("1")
static String stringForX() {
    return "oneX";
}

@Provides
@Named("2")
static String stringForA() {
    return "twoA";
}

@Provides
@Named("b1")
B provideB1(@Named("1") String s) {
    return new B(s);
}

@Provides
@Named("b2")
B provideB2(@Named("2") String s) {
    return new B(s);
}

}