2

Let's say I have the following classes and dagger module

public class Base implements IBase {
    private IDependency dependency; //IDependency is an interface

    Base(IDependency dependency) {
        this.dependency = dependency
    }
}

public class SubClass extends Base implements ISubclass {
    Base(IDependency dependency) {
        super(dependency)
    }
}

@Module
public class MyModule {

    // Let's assume some other class use SubClass and requires this
    @Provides
    ISubclass providesSubclass(IDependency dependency) {
        return new SubClass(dependency);
    }
}

If I add a new parameter to Base constructor, I'll have to go to MyModule and modify provides method to include this new parameter (besides obviusly chaging Base and Subclass constuctors). It seems to me that using propery injection I don't have this problem since I'm not using any constructor.

My feeling is that I might be doing something wrong or I have some concept wrong. I prefer constructor injection over property injection but right now I have to add a constructor parameter to a base class used by 40 other classes and not only I have to modify those 40 classes constructors, I also have to modify modules to reflect new constructors parameters.

Am I missing something? Am I correct if I say that doing constructor injection I'll write much more less code and maintenance will be easier?

StackOverflower
  • 5,463
  • 13
  • 58
  • 89
  • Possible duplicate of [Dependency injection through constructors or property setters?](http://stackoverflow.com/questions/1503584/dependency-injection-through-constructors-or-property-setters) – rghome Feb 11 '16 at 13:57

1 Answers1

1

Yes, you are missing some awesome feature: You can still use constructor injection in this case! And you don't even have to write it yourself.

If all of the dependencies can be provided, dagger can and will create the object for you. Given that you can provide IDependency you just need to modify your code like the following:

public class SubClass extends Base implements ISubclass {

    @Inject // Don't forget the annotation!
    public Base(IDependency dependency) {
        super(dependency)
    }
}

@Module
public class MyModule {

    @Provides
    ISubclass providesSubclass(SubClass subclass) {
        return subclass;
    }
}

You provide the interface, yet you depend on your implementation to provide it. Dagger will resolve this, and you can merrily add as many parameters to the constructor as you like. (Apart from the obvious changes to the actual constructors you already pointed out)

Don't forget the @Inject annotation!

David Medenjak
  • 33,993
  • 14
  • 106
  • 134