我正在使用Dagger 2中的新
dagger.android
包,在我的项目中注入Android依赖项。
- I need all my Activities to be a subclass of an abstract
BaseActivity
In my
BaseActivity
I have member variables to be injected. This way:abstract class BaseActivity : AppCompatActivity() { @Inject lateinit var prefs: MyPreferenceDataStore ...// more @Injected members }
I do it because I want subclasses of
BaseActiviy
can have access to injected members ofBaseActivity
:class SubClassActivity : BaseActivity() { override fun onCreate(savedInstanceState: Bundle) { val x = prefs.getXXX //use prefs variable from parent class } }
This is my ApplicationComponent:
@Singleton @Component(modules = arrayOf( ApplicationModule::class, ActivityBindingModule::class, AndroidSupportInjectionModule::class )) interface ApplicationComponent { @Component.Builder interface Builder { @BindsInstance fun application(application: Application): Builder fun build(): ApplicationComponent } fun inject(app: AndroidApplication) }
The
ApplicationModule
class has simple@Provides
annotated methods:@Module class ApplicationModule { @Singleton @Provides fun providesMyPreferenceDataStore(context: Context): MyPreferenceDataStore { return MyPreferenceDataStoreImpl(context) } // more @Provides annotated methods }
I think the problem is in my
ActivityBindingModule
@Module abstract class ActivityBindingModule { @PerActivity @ContributesAndroidInjector( modules = arrayOf(BaseActivityModule::class )) abstract fun bindBaseActivity(): BaseActivity @PerActivity @ContributesAndroidInjector( modules = arrayOf( BaseActivityModule::class )) abstract fun bindSubClassActivity(): SubClassActivity }
这是我到目前为止尝试过的:
Make the
bindSubClassActivity()
method not to depend ofBaseActivityModule::class
, didn't work.Move the
providesMyPreferenceDataStore
fromApplicationModule
to theBaseActivityModule
, so that the class is:@Module class BaseActivityModule { @PerActivity @Provides fun providesMyPreferenceDataStore(context: Context): MyPreferenceDataStore { return MyPreferenceDataStoreImpl(context) } }
这是我收到的错误:
Error: [dagger.android.AndroidInjector.inject(T)] com.example.BaseActivity cannot
be provided without an @Provides-annotated method.
This type supports members injection but cannot
be implicitly provided.