23

How would I create an instance of Dog with a component which provides Cat.

public final class Dog {
    private final Cat mCat;
    public final static String TAG = "Dog";

    @Inject public Dog(Cat cat) {
        mCat = cat;
        Log.e(TAG, "Dog class created");
    }
}

After experimenting with Dagger 2 for a while I have no idea how to use constructor injection – a hint would be nice, thanks.

Edit:
Whats wrong with the question? After using Dagger 2, following several tutorials and reading the official documentation I have no clue how to use the constructor injection feature, that's why I ask here. Instead of injecting the Cat dependency into Dog with @Inject I could write a DogModule providing a Dog object, but then Dog would be just a regular Java class. Field injection works great (there are a lot of examples showing how to use it) but what do I need to do to use constructor injection?

Tar
  • 8,529
  • 9
  • 56
  • 127
Paradiesstaub
  • 2,590
  • 2
  • 18
  • 28

1 Answers1

13

To create an object using the Dagger 2 constructor injection feature you need to add a method to a component which provides a Cat class.

@Component(
    dependencies = ApplicationComponent.class,
    modules = CatModule.class)
public interface ActivityComponent {
    void inject(final CatActivity a);
    // objects exposed to sub-components
    Cat cat();
    Dog dog();
}

An instance of Dog can then be retrived by calling [Component].dog().

final ActivityComponent comp = DaggerActivityComponent.builder()
            .applicationComponent(app.getApplicationComponent())
            .build();

final Dog d = comp.dog();
Tar
  • 8,529
  • 9
  • 56
  • 127
Paradiesstaub
  • 2,590
  • 2
  • 18
  • 28
  • 6
    This answer helped me very much. Thank you! However, I still wonder why there aren't any examples of constructor dependency injection of so popular framework. – Salivan May 27 '16 at 14:40