Reducing Boilerplate with the new HasAndroidInjector in Dagger 2.23

Nelson Osacky
1 min readMay 31, 2019

--

Dagger 2.23 introduces the HasAndroidInjector interface. It reduces some boilerplate in your Application class. Here is how you can destroy some of that boilerplate.

You might have an Application class that looks like this:

class MyApplication : Application(), HasActivityInjector, HasServiceInjector, HasBroadcastReceiverInjector, HasSupportFragmentInjector

And therefore you will also have some of these:

@Inject lateinit var androidActivityInjector : DispatchingAndroidInjector<Activity>@Inject lateinit var androidFragmentInjector : DispatchingAndroidInjector<Fragment>@Inject lateinit var androidBroadcastReceiverInjector : DispatchingAndroidInjector<BroadcastReceiver>@Inject lateinit var androidServiceInjector : DispatchingAndroidInjector<Service>

And you also have to implement those Has*Injector interfaces like so:

override fun activityInjector(): AndroidInjector<Activity> = androidActivityInjectoroverride fun serviceInjector(): AndroidInjector<Service> = androidServiceInjectoroverride fun broadcastReceiverInjector(): AndroidInjector<BroadcastReceiver> = androidBroadcastReceiverInjectoroverride fun supportFragmentInjector(): AndroidInjector<Fragment> = androidFragmentInjector

With Dagger 2.23, you can replace those 4 interfaces with just one:

class DaggerExampleApplication : Application(), HasAndroidInjector

And instead injecting 4 different injectors, you can just inject one:

@Inject lateinit var androidInjector : DispatchingAndroidInjector<Any>

Now you just have one method to implement:

override fun androidInjector(): AndroidInjector<Any> = androidInjector

Check out this sample commit performing this boilerplate reduction.

If you already extend from DaggerApplication, you will not need to make any changes.

Click here for the rest of the Dagger 2.23 release notes.

Thanks to the Dagger team for incorporating the feedback that dagger has a lot of boilerplate and setup!

P.S. Use Dagger 2.24 is the latest version.

Did I help save you some time? Fund my chocolate addiction.
I’m also available for Gradle help.

--

--

Nelson Osacky

Productivity Engineering @ Gradle. Former SoundCloud, Square. Lover of chocolate and running. osacky.com