Dagger2组件通用注入方法 [英] Dagger2 component generic inject method

查看:78
本文介绍了Dagger2组件通用注入方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的应用程序从Dagger1.0转换为dagger2.0,并具有包含许多 void inject(Activity/Fragment/Receiver/etc对象)方法的应用程序组件.

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.

使用dagger 1.0,我只能执行 objectGraph.inject(Object 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.

为什么我不能只拥有一种方法的组件:< T>void inject(T t); 吗?

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

供参考:我的当前组件:


public interface AppComponent {

    void inject(MyFirstActivity activity);

    void inject(MySecondActivity activity);

    void inject(MyFirstFragment fragment);

    void inject(MySecondFragment fragment);

    ...
}

我想要的组件


public interface AppComponent {
   <T> void inject(T object);
}

推荐答案

为什么我不能只拥有一种方法的组件:< T>无效注入(T t); ?

因为 dagger-2 使用代码生成,并且需要在编译时知道类型信息.没有它,就无法判断 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.

如果您编译第一个组件并检出生成的 Dagger * Component 源代码,则会看到每个 inject 方法都有其自己的工厂方法,并提供了所有给定类型的依赖关系 .

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可以注入超类中的成员,但不会注入潜在子类型的成员.同样,因为 dagger-2 依赖于编译时代码生成,所以这是不可能的.

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.

这篇关于Dagger2组件通用注入方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆