Dagger注入GoogleSignInClient报MissingBinding异常求助
解决Dagger/MissingBinding GoogleSignInClient注入异常
问题原因
你的AppModule绑定的GoogleSignInClient仅在ViewModelComponent内可用(通过@InstallIn(ViewModelComponent::class)和@ViewModelScoped限定),如果尝试在ViewModel以外的类(如Activity、Fragment)中注入该依赖,Dagger会因为找不到跨Component的绑定而抛出异常。
解决方案
方案1:在ViewModel中注入(推荐)
如果你的GoogleSignInClient是给ViewModel使用的,按以下步骤调整:
- 给ViewModel添加
@HiltViewModel注解,并通过构造函数注入GoogleSignInClient:
@HiltViewModel class AuthViewModel @Inject constructor( private val googleSignInClient: GoogleSignInClient ) : ViewModel() { // 这里编写你的业务逻辑 }
- 保持你原有的
AppModule代码不变,因为它的Scope和Component正好匹配ViewModel的依赖需求。
方案2:在Activity/Fragment中注入
如果需要在界面类中直接使用GoogleSignInClient,修改Module的Component和Scope配置:
- 更新
AppModule的安装组件和Scope:
@Module @InstallIn(SingletonComponent::class) // 换成SingletonComponent或ActivityComponent object AppModule { @Provides @Singleton // 对应SingletonComponent的Scope,若用ActivityComponent则换成@ActivityScoped fun providesGoogleSignInOptions(@ApplicationContext context: Context) = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(context.getString(R.string.web_client_id)) .requestEmail() .build() @Provides @Singleton fun providesGoogleSignInClient(gso: GoogleSignInOptions, @ApplicationContext context: Context) = GoogleSignIn.getClient(context, gso) }
- 在需要注入的Activity/Fragment上添加
@AndroidEntryPoint注解,并注入依赖:
@AndroidEntryPoint class AuthActivity : AppCompatActivity() { @Inject lateinit var googleSignInClient: GoogleSignInClient // 后续使用googleSignInClient即可 }
必要检查项
- 确保你的Application类已添加
@HiltAndroidApp注解 - 所有需要注入依赖的Activity/Fragment都标记了
@AndroidEntryPoint
内容的提问来源于stack exchange,提问作者mgok
相关产品推荐
相关产品推荐

