匕首父部件范围

发布于 2025-02-08 22:25:00 字数 120 浏览 2 评论 0原文

如果我将核心组件用作AppComponent的父组件,并且AppComponent的范围是Singleton。来自CoreComponent的所有依赖性是否都是单元很好?我的意思是,只会为父母提供的依赖项或多个创建一个实例吗?

If I use Core-component as parent component of my AppComponent , and the scope for the AppComponent is singleton. Is all the dependency derive from corecomponent would be singletone ? I mean Only one instance will be created for parent provided dependencies or multiple ?

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

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

发布评论

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

评论(1

唔猫 2025-02-15 22:25:00

@singleton并不是说“单个实例”,正如我们从荒原模式中所知道的那样。

基本上,当我们谈论单例时,我们会考虑通过应用程序的生命周期创建的一个实例。

当我们在匕首中说@singleton时,只是“范围的名称”。基本上是指通过该组件的生命周期创建的一个实例。

这就是某些人不使用@Singleton的原因,而是Cretate @perapp注释,因此我们更清楚和明显。

我的意思是 - 您指出父母有@singleton范围。没关系。无论如何,这可能是 @ @thecope。您需要关心的是以下内容:

  • 如果未范围从父组件开始(您仅放置@provides,但没有@somescope注释),每次使用此依赖关系(提供)在某个地方将是一个将是一个新实例。

  • 另一方面 - 如果父组件具有一些范围的依赖关系,例如您的情况@singleton或我说的那样:@whateverscope-当组件还活着时,它将仅提供一个实例,即您能够创建的时间,销毁,重新创建许多儿童组件。

  • 但是,如果您重新创建父母,即使您使用@Singleton进行范围 - 您将拥有同一应用程序生命周期的范围依赖关系的第二个实例。

@Singleton does not mean "a single instance" as we know it from the desing pattern.

Basically when we talk about singletons we think about a Single instance created through the lifecycle of the application.

When we say @Singleton in Dagger - it is just "a name of a scope". Basically it means - a single instance created through the lifecycle of that Component.

That is the reason some people do not use @Singleton, but cretate @PerApp annotation so it us more clear and obvious.

My point is - you are pointing out the parent has a @Singleton scope. It doesn't matter. It could be the @Whatever scope. What you need to care about is the following:

  • If dependencies comming from a parent Component are not scoped(you only put @Provides, but no @SomeScope annotation) every time this dependency is used(provided) somewhere it will be a new instance.

  • On the other hand - if the parent Component has some scoped dependencies like in your case @Singleton or like I said: @WhateverScope - while the Component is alive it will provide only one instance for the time you are able to create, destroy, recreate many child components.

  • But if you recreate the parent, even if you scope it with @Singleton - you will have a 2nd instance of the scoped dependencies for the same application lifecycle.

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