我在应用模块中使用来自外部模块的AuthenticationRequest对象。我将此对象作为依赖项提供给我的AccountRepository。这就是我如何在应用模块中定义我的依赖项的方法。
@InstallIn(SingletonComponent::class)
@Module
class ApplicationModule {
@Provides
@Singleton
fun provideRepository(
authenticationRequest: AuthenticationRequest,
accountDao: AccountDao
) = AccountRepository(authenticationRequestFactory, accountDao)
}外部模块中的AuthenticationRequest构造函数:
class AuthenticationRequest(
api: AuthenticationApi,
apiError : ApiError = ApiErrorImpl()
) : Request<AuthenticationApi>(api, apiError)AccountRepository:
class AccountRepository @Inject constructor(
private val authenticationRequestFactory: AuthenticationRequestFactory,
private val accountDao: AccountDao
) {....}但是我得到了以下错误消息:Dagger/MissingBinding] com.external.auth.AuthenticationRequest不能在没有@Inject构造函数或@Provi富于注释的方法的情况下提供。
如何正确注入AuthenticationRequest对象?注意,定义此对象的模块不使用Dagger-Hilt。不过它用的是匕首-2。任何指示都是很好的。
注:项目结构为
|-- :app
-- :external module发布于 2021-11-26 23:29:11
Dagger/Hilt只能创建具有@Inject构造函数的类。正如您所说,AuthenticationRequest类不是这样设置的。
您需要添加一个@Provides方法,让Dagger知道如何创建这个类:
@InstallIn(SingletonComponent::class)
@Module
object ApplicationModule {
@Provides
@Singleton
fun provideAuthenticationRequest(
someDependency: SomeDependency,
anotherOne: AnotherOne,
): AuthenticationRequest {
return AuthenticationRequest(
someDependency,
anotherOne
)
}
@Provides
@Singleton
fun provideSomeDependency(): SomeDependency {
return SomeDependency()
}
@Provides
@Singleton
fun provideAnotherOne(
evenMoreDependency: EvenMoreDependency
): AnotherOne {
return AnotherOne(evenMoreDependency)
}
@Provides
@Singleton
fun provideEvenMoreDependency(): EvenMoreDependency {
return EvenMoreDependency()
}
}正如洗礼说的,这应该是一个对象。在创建@Binds方法时,您只需要创建一个(抽象)类,因为希尔特要做一个实现。但在这种情况下不需要这个。
至于它是否应该是一个组成部分-这真的取决于你。我想说,如果您不确定然后将它们全部放在一个对象中,那么稍后将它们迁移到自己的文件中并不是什么大不了的事。
更多信息:“满意属地”下的https://dagger.dev/dev-guide/
https://stackoverflow.com/questions/70130867
复制相似问题