我正在尝试在我的应用程序中使用Dagger 2支持来实现MVP模式
这里是对象:
class BaseApplication : Application(), HasActivityInjector
{
override fun onCreate()
{
super.onCreate()
initDi()
}
private fun initDi(){
DaggerAppComponent.builder().application(this).build().inject(this)
}
@Inject lateinit var activityInjector: DispatchingAndroidInjector<Activity>
override fun activityInjector(): AndroidInjector<Activity>
{
return activityInjector
}
}
@Singleton
@Component(modules = arrayOf(AndroidInjectionModule::class, AppModule::class, ActivityBuilder::class))
interface AppComponent
{
@Component.Builder
interface Builder
{
@BindsInstance
fun application(application: Application): Builder
fun build(): AppComponent
}
fun inject(app: BaseApplication)
}
@Module
class AppModule
{
@Provides
@Singleton
internal fun provideContext(application: Application): Context
{
return application
}
}
@Module
abstract class ActivityBuilder
{
@ContributesAndroidInjector(modules = arrayOf(LoginFragmentProvider::class))
internal abstract fun bindAuthenticationActivity(): AuthenticationActivity
}
@Module
public abstract class LoginFragmentProvider
{
@ContributesAndroidInjector
abstract LoginFragment provideLoginFragmentFactory();
}
class AuthenticationActivity : AppCompatActivity(), HasSupportFragmentInjector
{
@Inject lateinit var androidInjector: DispatchingAndroidInjector<Fragment>
override fun supportFragmentInjector(): AndroidInjector<Fragment>
{
return androidInjector
}
}
class LoginFragment : Fragment() {
override fun onAttach(context: Context?)
{
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
问题是,当登录片段调用 AndroidSupportInjection.inject(this)时,会调用AuthenticationActivity supportFragmentInjector ,但是 androidInjector 仍然为空
结果,我得到了异常(exception):
java.lang.RuntimeException:无法启动 Activity ..... AuthenticationActivity}:kotlin.UninitializedPropertyAccessException:lateinit属性androidInjector尚未初始化
我不确定如何解决此问题
提前致谢
最佳答案
我认为您忘记注入(inject)AuthenticationActivity
了。您应该在AndroidInjection
中调用onCreate
。
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
}
编辑:您可以检查我的示例存储库以获取更多信息。 https://github.com/savepopulation/dc-tracker