Kotlin error: Dagger does not support injection into static fields
Kotlin error: Dagger does not support injection into static fields
我尝试在我的 Retrofit 项目中使用 Dagger 进行依赖注入,但是当我构建代码时它抛出这个错误:Dagger 不支持注入静态字段。有谁知道为什么我会收到此错误?我不知道我做错了什么。
MianActivity.kt:
@Inject
lateinit var mApiService : ApiService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var retroComponent = DaggerRetroComponent.create()
retroComponent.inject(this)
}
RetroComponet.kt
@Singleton
@Component(modules = [ServiceBuilderModule::class])
interface RetroComponent {
//Field Injection
fun inject(mainActivity: MainActivity)
}
ServiceBuilder.kt
@Module
object ServiceBuilderModule {
val baseUrl = "https://dog-facts-api.herokuapp.com"
@Singleton
@Provides
fun retrofitInstance(): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
fun getRetroServiceInterface(retrofit: Retrofit): ApiService {
return retrofit.create(ApiService::class.java)
}
ApiService.kt
interface ApiService {
@GET("/api/v1/resources/dogs")
suspend fun getDogFact(@Query("index") index: String): Response<List<DogFactModel>>
}
替换:
@Inject
lateinit var mApiService : ApiService
class MainActivity : AppCompatActivity() {
与:
class MainActivity : AppCompatActivity() {
@Inject
lateinit var mApiService : ApiService
mApiService
需要 MainActivity
内的 属性,而不是 top-level 属性.
我尝试在我的 Retrofit 项目中使用 Dagger 进行依赖注入,但是当我构建代码时它抛出这个错误:Dagger 不支持注入静态字段。有谁知道为什么我会收到此错误?我不知道我做错了什么。
MianActivity.kt:
@Inject
lateinit var mApiService : ApiService
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var retroComponent = DaggerRetroComponent.create()
retroComponent.inject(this)
}
RetroComponet.kt
@Singleton
@Component(modules = [ServiceBuilderModule::class])
interface RetroComponent {
//Field Injection
fun inject(mainActivity: MainActivity)
}
ServiceBuilder.kt
@Module
object ServiceBuilderModule {
val baseUrl = "https://dog-facts-api.herokuapp.com"
@Singleton
@Provides
fun retrofitInstance(): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Singleton
@Provides
fun getRetroServiceInterface(retrofit: Retrofit): ApiService {
return retrofit.create(ApiService::class.java)
}
ApiService.kt
interface ApiService {
@GET("/api/v1/resources/dogs")
suspend fun getDogFact(@Query("index") index: String): Response<List<DogFactModel>>
}
替换:
@Inject
lateinit var mApiService : ApiService
class MainActivity : AppCompatActivity() {
与:
class MainActivity : AppCompatActivity() {
@Inject
lateinit var mApiService : ApiService
mApiService
需要 MainActivity
内的 属性,而不是 top-level 属性.