![](/img/trans.png)
[英]How can i inject a class that needs context into Broadcast Receiver with hilt?
[英]Using Hilt, how to inject into a class that does not have a context?
我有一個名為NetworkManager
的 class 。 由於它不是 Android 組件之一,我正在使用自定義入口點NetworkManagerEntryPoint
,它返回NetworkClient
object 這是我想要注入的一個fun
。
現在,要使用 Hilt 注入此 class 的實例,我相信我需要使用EntryPointAccessors
中的 Helper 方法之一。 但所有這些都需要參考 android 組件。 那么,我真的必須將 android 組件(如 Context)傳遞給我的 class 以使用 Hilt 注入 object 嗎?
class NetworkManager() {
@InstallIn(SingletonComponent::class)
@EntryPoint
interface NetworkManagerEntryPoint {
fun getNetworkClient(): NetworkClient
}
var defaultNetworkClient: NetworkClient = EntryPointAccessors.fromApplication(
context, // Do I have to pass a context to this class to use Hilt?
NetworkManagerEntryPoint::class.java
).getNetworkClient()
fun <R : Any> executeRequest(
request:Request<R>,
networkClient: NetworkClient = defaultNetworkClient
): Response<R> {
// Do some operation
}
}
嗨,也許你可以試試我做過的這種方式,我遵循 mvvm 模式
我的 RetrofitApi
interface RetrofitApi {
@GET("endpoint")
suspend fun getApi():Response<RetrofitApiResponse>
}
我的網絡模塊
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule{
@Singleton
@Provides
fun provideApi(): RetrofitApi = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(RetrofitApi::class.java)
@Singleton
@Provides
fun provideRepository(retrofitApi:RetrofitApi) : MainRepository =
DefualtMainRepository(retrofitApi)
}
這個模塊被注入我的存儲庫
class DefualtMainRepository @Inject constructor(
val retrofitApi: RetrofitApi
):MainRepository {
override suspend fun getQuotes(): Resource<RetrofitApiResponse> {
val response = retrofitApi.getApi()
val result = response.body()
if (response.successful){
}
}
}
如果您有興趣,我在我的 github 中有完整的項目,甚至寫了一篇解釋它的中等文章,希望我的回答對您有所幫助https://zaidzakir.medium.com/a-simple-android-app-using-mvvm-dagger -hilt-e9f45381f1bc
好的。 @Zaid Zakir 的回答告訴我,如果不是字段注入,我可以通過構造函數參數注入對象。 所以,我的解決方案最終看起來像這樣。
@Singleton
class NetworkManager @Inject constructor(
var defaultNetworkClient: NetworkClient
) {
fun <R : Any> executeRequest(
request:Request<R>,
networkClient: NetworkClient = defaultNetworkClient
): Response<R> {
// Do some operation
}
}
在另一個名為NetworkClientModule
的 class 中,我有這個,
@Module
@InstallIn(SingletonComponent::class)
abstract class NetworkClientModule {
@Binds @Singleton
abstract fun bindDefaultNetworkClient(impl: DefaultNetworkClient): NetworkClient
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.