Search code examples
androiddependency-injectionroboguicedagger-2

Mimic RoboGuice injection in Dagger 2


I started learning Dagger 2 and one thing hit me hard: mechanism of injection. I was using RoboGuice earlier and my projects look like MVP mechanism

  • Views (Activity/Fragment),
  • Controllers (all logic),
  • and Models (simple objects)

So Controllers are @Singleton and in every view I always called only @Inject DedicatedController. It works great. But in Dagger 2 to achieve the same I need to define every Controller in Modules (according to patterns probably even in many files), and define in Component every View which is target to injection.

This is in my opinion horrible and destroying the idea of making coding simpler with Dagger 2. Do you have any solutions on how to simplify this mechanism and to avoid the overhead?


Solution

  • If you're going to use 3rd party library, you enjoy its advantages and accept its limitation. If in your opinion the limitations outweigh the added value, don't use it. This is true for every library.

    Regarding Dagger2, dagger works with components and modules - that's just the way it's built. Having said that - there is a very cool feature that lets you get around this sometimes - and that is the injected constructors.

    When a constructor is marked with the @Inject annotation, it does two things:

    1. Dagger2 knows the class dependencies.
    2. Dagger2 knows how to instantiate that class.

    That means that classes with an injected constructor do not need to be created by a module, and do not need to know about components.

    This can not be done for Activities and Fragments since you have no control over when they'll be instantiated.

    TL;DR

    If both your Models and Presenters have an injected constructor, then only your Views (Activities and Fragments) will need to know a Component.