我有一个在其中使用Dagger的项目。我添加了以下课程:
private const val CATEGORY = "category"
@Singleton
class Storage @Inject constructor(
private var prefs: SharedPreferences,
private var editor: SharedPreferences.Editor,
private var adapter: JsonAdapter<List<Category>>,
context: Context
) {
init {
prefs = PreferenceManager.getDefaultSharedPreferences(context)
editor = prefs.edit()
val moshi = Moshi.Builder().build()
val listType = Types.newParameterizedType(List::class.java, Category::class.java)
adapter = moshi.adapter(listType)
}
fun setCategories(categories: List<Category>) {
editor.putString(CATEGORY, adapter.toJson(categories))
}
fun getCategories() = adapter.fromJson(prefs.getString(CATEGORY, null))
}
构建时,收到以下匕首编译时错误:
error: [Dagger/MissingBinding] android.content.SharedPreferences cannot be provided without an @Provides-annotated method.
public abstract interface AppComponent extends dagger.android.AndroidInjector<com.sample.android.cafebazaar.FoursquareApplication> {
^
android.content.SharedPreferences is injected at
com.sample.android.cafebazaar.util.Storage(prefs, …)
com.sample.android.cafebazaar.util.Storage is injected at
com.sample.android.cafebazaar.ui.MainFragment.storage
com.sample.android.cafebazaar.ui.MainFragment is injected at
dagger.android.AndroidInjector.inject(T) [com.sample.android.cafebazaar.di.AppComponent → com.sample.android.cafebazaar.di.ActivityBindingModule_MainActivity$app_debug.MainActivitySubcomponent → com.sample.android.cafebazaar.di.MainModule_MainFragment$app_debug.MainFragmentSubcomponent]
我该如何解决?
如果您在@Inject带注释的构造函数中具有任何属性,则意味着Dagger试图为您创建那些属性。换句话说,这些是类Storage中的依赖项。我认为您至少需要将其从构造函数中移开,因为我看到您是在代码中自行创建的。
尝试一下是否有帮助:
@Singleton
class Storage @Inject constructor(context: Context) {
private val prefs: SharedPreferences
private val editor: SharedPreferences.Editor
private val adapter: JsonAdapter<List<Category>>
init {
prefs = PreferenceManager.getDefaultSharedPreferences(context)
editor = prefs.edit()
val moshi = Moshi.Builder().build()
val listType = Types.newParameterizedType(List::class.java, Category::class.java)
adapter = moshi.adapter(listType)
}