square / dagger

A fast dependency injector for Android and Java.
https://square.github.io/dagger/
Apache License 2.0
7.3k stars 3.07k forks source link

@named annotation with condition #540

Closed alorma closed 8 years ago

alorma commented 8 years ago

I get a use case where i needed two different interfaces to be provided with the same name, depending on API version (android)

@provides
@CustomScope
@Named("NotificationsJobManager")
AppJobManager getAlarmManagerJobManager() {...}

@provides
@CustomScope
@Named("NotificationsJobManager")
AppJobManager getJobSchedulerJobManager() {...}

JobScheduler appears on Android Lollipop, so it will be great to have something like:

@provides
@CustomScope
@Named("NotificationsJobManager")
AppJobManager getAlarmManagerJobManager() {...}

@provides
@CustomScope
@Named("NotificationsJobManager")
@Condition(Build.Version.SDK_CODE == 21)
AppJobManager getJobSchedulerJobManager() {...}

This will work like this:

JakeWharton commented 8 years ago

Move the condition inside the method and alter the return value based on it. Alternatively, you can apply different modules based on the API level. Both of these are vastly more powerful since you can actually use runtime state in your conditionals (something that is required for your non-working example).