匕首柄:注释 class @Singleton 和提供函数 @Singleton 之间的区别

Dagger hilt: Difference between annotating a class @Singleton and a provides function @Singleton

我的问题非常简单直接:两个注释/示例之间有什么区别:

例子一

@Singleton
class MySingletonClass() {}

@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {
   @Provides
   fun provideMySingletonClass() = MySingletonClass()
}

例子二

class MySingletonClass() {}

@Module
@InstallIn(FragmentComponent::class)
abstract class MyFragmentModule {

   @Singleton
   @Provides
   fun provideMySingletonClass() = MySingletonClass()
}

我知道的唯一区别是,第二个示例给我以下错误:

error: [Dagger/IncompatiblyScopedBindings] FragmentC scoped with @dagger.hilt.android.scopes.FragmentScoped may not reference bindings with different scopes:

这是否意味着示例 1 中的 @Singleton 注释被简单地忽略了?

在示例一中,您的 @Singleton 注释被忽略,但这只是因为您在 @Provides 方法中自己调用了构造函数 。因为 Dagger 不与您的 MySingletonClass 构造函数交互,所以它无法读取或使用注释。

如果你的 @Singleton class MySingletonClass 有一个 @Inject constructor——即使是一个空的——那么 Dagger 将能够直接与它交互 只要你也 删除将覆盖构造函数检测的 @Provides fun。完成后,@Singleton 的行为在两种语法中都是相同的。


关于错误消息“错误:[Dagger/IncompatiblyScopedBindings] XXX scoped with @YYY may not reference bindings with different scopes”:@Andrew 这里真正的问题是在示例二中,您试图在 FragmentComponent 中安装的模块中声明 @Singleton 绑定。 @Singleton 绑定只能发生在@Singleton 组件中,which in Hilt is SingletonComponent。我记不太清了,但我认为您的示例一(经过我描述的编辑)可以使用单例行为并且不会出现错误,因为 Dagger 会自动 select 层次结构中的适当组件来安装您的 MySingletonClass .