使用 dagger2 进行依赖注入时,我可以只注入超类吗? [英] Can I just inject super class when use dagger2 for dependency injection?

查看:35
本文介绍了使用 dagger2 进行依赖注入时,我可以只注入超类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的 android 应用程序中使用 Dagger2 进行 DI.我发现我必须为每个使用 @Inject 字段的类编写注入方法.有没有一种方法可以只注入父类,这样我就不必在每个子类上调用注入?以活动为例.我有一个 BaseActivity ,每个 Activity 都从它扩展.有没有一种方法可以在组件中为 BaseActivity 创建一个注入方法,然后在 BaseActivity 的 onCreate 中调用注入,然后子活动中的 @inject 字段会自动注入?

I use Dagger2 for DI in my android application. I found that I have to write inject method for every class that uses @Inject field. Is there a way that I can just inject the parent class so that I don't have to call inject on every subclass? Take Activity for example. I have a BaseActivity that that every Activity extends from. Is there a way that I can just create an inject method in the component for BaseActivity and just call inject in BaseActivity's onCreate, and @inject fields in sub activities get injected automatically?

推荐答案

现在无法完成.Gregory Kick 的解释(来自此处):

It cannot be done right now. Explanation by Gregory Kick (from here):

以下是成员注入方法的工作原理:

Here's how members injection methods work:

  1. 您可以为在其类层次结构中的任何位置具有 @Inject 的任何类型创建成员注入方法.如果没有,你会得到一个错误.
  2. 将注入整个类型层次结构中所有 @Inject ed 成员:参数类型和所有超类型.
  3. 没有成员将被@Inject用于参数类型的子类型.
  1. You can make a members injection method for any type that has @Inject anywhere in its class hierarchy. If it doesn't, you'll get an error.
  2. All @Injected members in the entire type hierarchy will be injected: the argument type and all supertypes.
  3. No members will be @Injected for subtypes of the argument type.

这个问题在这里此处,关注这些更新.但它不太可能很快改变,因为 Dagger 2 即将发布.

This issue was discussed here and here, follow up these for updates. But it is unlikely to change soon, cause Dagger 2 is close to release.

这篇关于使用 dagger2 进行依赖注入时,我可以只注入超类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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