Dagger 2 – Named

With the named attribute, you are able to create multiple instances of objects of the same class.  This is useful if you are configuring multiple objects that just have different configuration settings.

This is done using the @Named attribute which allows you to identify different instances that have the same class.

@Module
public class ServiceModule {
 
  @Provides
  @Singleton
  @Named("customerService")
  public ServiceGenerator provideCustomerServiceGenerator() {
    return new ServiceGenerator(Config.CUSTOMER_BASE_URL);
  }
 
  @Provides
  @Singleton
  @Named("paymentService")
  public ServiceGenerator providePaymentServiceGenerator() {
    return new ServiceGenerator(Config.PAYMENT_BASE_URL);
  }
}

Then to inject the named instance in to your application you include the named value as part of the @Inject annotation.

class MyActivity {
  @Inject @Named("customerService") ServiceGenerator customerService;
  @Inject @Named("paymentService") ServiceGenerator paymentService;
  ...
}

You can also inject them as part of an injected constructor.

class Transaction {

  @Inject
  public Transaction(@Named("paymentService") ServiceGenerator service) { 
    ...
  }
}

References:

Leave a Reply

Your email address will not be published. Required fields are marked *