[英]kotlin dagger retrofit field injection
When trying to inject field variables using dagger I'm getting null. 当尝试使用匕首注入字段变量时,我得到的是null。 Here are the files. 这是文件。 Some are in Java and some in Kotlin 有些使用Java,有些使用Kotlin
App.java App.java
public class App extends DaggerApplication{
@Override
protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
return DaggerAppComponent.builder().application(this).build();
}
}
AppComponent.kt AppComponent.kt
@Singleton
@Component(modules = arrayOf(
NetworkModule::class,
ApplicationModule::class,
AndroidSupportInjectionModule::class
))
interface AppComponent : AndroidInjector<TBApplication> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: Application): AppComponent.Builder
fun build(): AppComponent
}
}
NetworkModule.kt NetworkModule.kt
@Module
class NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient {
val builder = OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
builder.addInterceptor(interceptor).build()
}
return builder.build()
}
@Singleton
@Provides
fun provideRetrofit(client: OkHttpClient): Retrofit {
val retrofit = Retrofit.Builder()
.baseUrl(BaseApi.SITE_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(client)
.build();
return retrofit
}
}
// Repository where injection should be done //应该注入的存储库
class Repository {
private var examsService: BlogExamsService
@Inject
var retrofit: Retrofit? = null
init {
// retrofit is null here
examsService = retrofit?.create(BlogExamsService::class.java)!!
}
}
Field injection won't work as you do not run inject()
method. 字段注入将不起作用,因为您没有运行inject()
方法。
To make it work with your approach you should call in you Repository
class: 为了使其适合您的方法,您应该调用Repository
类:
App.self.getComponent().inject(this)
Where: 哪里:
self
is static
instance of your application self
是应用程序的static
实例
getComponent()
public getter for ApplicationComponent
getComponent()
ApplicationComponent
公共获取器
Though I would not recommend it in your case, it is a misuse of DI framework. 尽管我不建议您这样做,但这是对DI框架的滥用。
You should create RepositoryModule
and @Provide
instance of Repository
the same as you have done with NetworkModule
. 您应该像使用NetworkModule
一样创建RepositoryModule
和Repository
的@Provide
实例。
Change your Repository
to: 将您的Repository
更改为:
class Repository {
private var examsService: BlogExamsService
@Inject
constructor(retrofit: Retrofit) {
examsService = retrofit.create(BlogExamsService::class.java)!!
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.