Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dagger2 component generic inject method

I converted my app from Dagger1.0 to dagger2.0, and have an app component with many void inject(Activity/Fragment/Receiver/etc object) methods.

With dagger 1.0 I just could just do objectGraph.inject(Object object) but now my component has to have a method for every single class that gets dependencies injected to it.

Why can't I just have a component that has one method: <T> void inject(T t); ?

For reference: My component right now:


public interface AppComponent {

    void inject(MyFirstActivity activity);

    void inject(MySecondActivity activity);

    void inject(MyFirstFragment fragment);

    void inject(MySecondFragment fragment);

    ...
}

The component I want:


public interface AppComponent {
   <T> void inject(T object);
}
like image 837
Prem Avatar asked Mar 03 '16 22:03

Prem


People also ask

What is dagger2 and why do you use it?

Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.

What is dagger2 component?

Components are essentially the glue that holds everything together. They are a way of telling Dagger 2 what dependencies should be bundled together and made available to a given instance so they can be used. They provide a way for a class to request dependencies being injected through their @Inject annotation.

What is @inject in Android?

Dependency injection provides your app with the following advantages: Reusability of classes and decoupling of dependencies: It's easier to swap out implementations of a dependency.

What is dagger injection?

Dagger is a fully static, compile-time dependency injection framework for Java, Kotlin, and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.


1 Answers

Why can't I just have a component that has one method: <T> void inject(T t);?

Because dagger-2 uses code generation and needs to know the type information at compile time. Without it, there is no way to tell which dependencies T would need—therefore code generation would be impossible.

If you compile your first component and check out the generated Dagger*Component source code, you will see that each inject method gets its own factory method, providing all of the dependencies for the given type.

This is the same for injecting subclasses. You can check out the paragraph A note about covariance in the component documentation. Because the superclass type is known, dagger can inject members in the superclass, but it will not inject members of potential subtypes. Again, because dagger-2 relies on compile time code generation this is not possible.

like image 195
David Medenjak Avatar answered Nov 11 '22 05:11

David Medenjak