Dagger 2: avoid exporting private dependencies

Let's say I have a module where I want to export an instance A

. However, this A

requires that instances B

and are C

passed in the constructor. Therefore, we will also declare them in the module:

public class SampleModule {

    @Provides
    @Singleton
    A provideA(B b, C c){
        return new A(b, c);
    }

    @Provides
    @Singleton
    B provideB(){
        return new B();
    }

    @Provides
    @Singleton
    C provideC(){
        return new C(); 
    }
}

      

It works, but now B

and C

also available elsewhere in the code. I want their private and coerced client classes to only be able to access A

.

Is there a way to achieve this?

+3


source to share


1 answer


The easiest way to achieve this goal is to associate the types you don't want to receive (in this case, B

and C

) with @Qualifier

which is not available.

Then, if B

u C

can be accessed from outside the module in order to enter them, you will need to provide a qualifier that is not.



@Module
public final class SampleModule {
  @Qualifier
  @Retention(RUNTIME)
  private @interface SampleModuleOnly {}

  @Provides
  @Singleton
  static A provideA(@SampleModuleOnly B b, @SampleModuleOnly C c){
    return new A(b, c);
  }

  @Provides
  @SampleModuleOnly 
  @Singleton
  static B provideB(){
    return new B();
  }

  @Provides
  @SampleModuleOnly 
  @Singleton
  static C provideC(){
    return new C(); 
  }
}

      

+3


source







All Articles