Skip to content
Advertisement

Dagger Dependency Injection Provider with Qualifier

I’d like to get a confirmation that: if two providers providing the same type of instance, one with qualifier and the other one without, would this work?

// Existing provider
@Singleton
@Provides
static MetricsCollectorFactory provideMetricsCollectorFactory(){}

// New one to be added
@Singleton
@Provides
@VersionBasedMetricsCollectorFactory
static MetricsCollectorFactory provideVersionBasedMetricsCollectorFactory(){}

For the following two cases, especially the TestClass1, will Dagger know which MetricsCollectorFactory to inject?

@Inject
TestClass1(MetricsCollectorFactory basicFactory)

@Inject
TestClass2(@VersionBasedMetricsCollectorFactory MetricsCollectorFactory basicFactory)

Advertisement

Answer

Yes, as on the Dagger dev guide, there are zero or one qualifier instances per key or binding, and absent is different than present.

However, from a readability perspective, you might consider avoiding letting the two coexist—particularly if your team is unfamiliar with Dagger. Your @VersionBasedMetricsCollectorFactory MetricsCollectorFactory might wind up as a field metricsCollectorFactory, which might cause an unfamiliar developer to inject a bare MetricsCollectorFactory instead of a desired @VersionBasedMetricsCollectorFactory MetricsCollectorFactory. In contrast, introducing an alternative like @Default MetricsCollectorFactory might be helpful, or at least would provide a useful compilation error to encourage a more careful reading of the injection key.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement