将注射字段注入任何范围的任何类

发布于 2025-01-25 10:16:30 字数 270 浏览 0 评论 0原文

假设我有一个类A,

class A ()

我想将a的实例注入 b 中,然后让刀具或匕首处理它。

Class B {

  @Inject lateinit var a: A 

}

假设B类是一个普通的类,没有上下文,例如ViewModel或其他任何内容,那么什么是正确的步骤(如果可能的话),这样我就可以使用实例a而无需手动init。

Suppose that I have a class A

class A ()

I want to inject an instance of A as a field into class B and let Hilt or Dagger to handle it.

Class B {

  @Inject lateinit var a: A 

}

Let say class B is a plain class, has no context, e.g viewmodel or anything, what are the proper steps (if possible) so I can use the instance a without manual init.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心的憧憬 2025-02-01 10:16:30

如果您可以访问B类的构造函数,则可以作为这样的参数传递:

class B @Inject constructor(
    private val classA : A 
){
     //...
}

否则,您可以使用@entrypoints
要了解有关@entrypoint的更多详细信息,您可以单击下面的链接:

https://developer.android.com/training/depparency-injoction/hilt-android-android-android#not-supported

If you can access constructor of class B you can pass as an argument like that:

class B @Inject constructor(
    private val classA : A 
){
     //...
}

Otherwise you can use @EntryPoints.
To learn more details about @EntryPoint, you can click the link below:

https://developer.android.com/training/dependency-injection/hilt-android#not-supported

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文