简体   繁体   English

Dagger2组件通用注入方法

[英]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. 我将我的应用程序从Dagger1.0转换为dagger2.0,并且有一个包含许多void inject(Activity/Fragment/Receiver/etc object)方法的应用程序组件。

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. 使用dagger 1.0,我只能执行objectGraph.inject(Object object)但是现在我的组件必须为每个要注入依赖项的类提供一个方法。

Why can't I just have a component that has one method: <T> void inject(T t); 为什么我不能只有一个具有一种方法的组件: <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);
}

Why can't I just have a component that has one method: <T> void inject(T t); 为什么我不能只有一个具有一种方法的组件: <T> void inject(T t); ?

Because dagger-2 uses code generation and needs to know the type information at compile time. 因为dagger-2使用代码生成,并且需要在编译时知道类型信息。 Without it, there is no way to tell which dependencies T would need—therefore code generation would be impossible. 没有它,就无法确定T需要哪些依赖项-因此将无法生成代码。

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 . 如果编译第一个组件并检查生成的Dagger*Component源代码,您将看到每个inject方法都具有自己的工厂方法,并提供给定类型的所有依赖关系。

This is the same for injecting subclasses. 这与注入子类相同。 You can check out the paragraph A note about covariance in the component documentation. 您可以在组件文档中查看有关协方差的说明A段落。 Because the superclass type is known, dagger can inject members in the superclass, but it will not inject members of potential subtypes. 由于超类类型是已知的,因此dagger可以注入超类中的成员,但不会注入潜在子类型的成员。 Again, because dagger-2 relies on compile time code generation this is not possible. 同样,由于dagger-2依赖于编译时代码生成,因此这是不可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM