kotlin dagger改装现场注射

时间:2018-03-19 20:48:15

标签: java android kotlin dagger-2

当尝试使用dagger注入字段变量时,我得到null。这是文件。有些是Java,有些是Kotlin

App.java

   public class App extends DaggerApplication{


    @Override
    protected AndroidInjector<? extends DaggerApplication> applicationInjector() {
        return DaggerAppComponent.builder().application(this).build();
    }
}

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

@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
    }


}

//应该完成注射的存储库

    class Repository {

        private var examsService: BlogExamsService

        @Inject
        var retrofit: Retrofit? = null

        init {
            // retrofit is null here
            examsService = retrofit?.create(BlogExamsService::class.java)!!
        }
   }

2 个答案:

答案 0 :(得分:2)

由于您没有运行inject()方法,因此无法进行字段注入。

要使其与您的方法一起使用,您应该打电话给Repository课程:

App.self.getComponent().inject(this)

其中:

self是您应用的static个实例

getComponent()

ApplicationComponent公众获取者

虽然在你的情况下我不推荐它,但它是对DI框架的误用。

您应该像RepositoryModule一样创建@ProvideRepository NetworkModule实例。

答案 1 :(得分:0)

将您的Repository更改为:

class Repository {

    private var examsService: BlogExamsService

    @Inject
    constructor(retrofit: Retrofit) {
        examsService = retrofit.create(BlogExamsService::class.java)!!
    }
}