Android - Dagger 2:无法提供通过应用程序组件提供的依赖关系
问题描述:
通过应用程序的应用程序组件提供的依赖关系没有单个实例。 我有以下代码:Android - Dagger 2:无法提供通过应用程序组件提供的依赖关系
@Component (modules = AppModule.class)
public interface AppComponent {
SharedPreferences getSharedPreferences();
}
@Module
public class AppModule {
private Context appContext;
private String prefFile;
public AppModule(@NonNull Context appContext, @NonNull String prefFile) {
this.appContext = appContext;
this.prefFile = prefFile;
}
@Provides
public SharedPreferences providePreferences(){
return new AppSharedPreferences(appContext, prefFile);
}
}
@Singleton
public class AppSharedPreferences implements SharedPreferences{
public AppSharedPreferences(Context appContext, String prefFile)
//Some code
}
public class AppApplication extends Application {
private AppComponent appComponent;
private InteractorsComponent interactorsComponent;
@Override
public void onCreate() {
super.onCreate();
appComponent = DaggerAppComponent.builder().appModule(new AppModule(getApplicationContext(), "PREF_STORE_NAME")).build();
interactorsComponent = DaggerInteractorsComponent.builder().appComponent(appComponent).build();
}
public AppComponent getAppComponent() {
return appComponent;
}
public InteractorsComponent getInteractorsComponent() {
return interactorsComponent;
}
}
@Module
abstract class InteractorsModule {
@Singleton
@Binds
abstract InteractorA provideInteractorA(AppInteractorA interactor);
@Singleton
@Binds
abstract InteractorB provideInteractorB(AppInteractorB interactor);
}
@Singleton
@Component (modules = InteractorsModule.class, dependencies = AppComponent.class)
public interface InteractorsComponent {
InteractorA getInteractorA();
InteractorB getInteractorB();
}
@Singleton
class AppInteractorA implements InteractorA {
private AppSharedPreferences pref;
@Inject
public AppInteractor(@NonNull AppSharedPreferences pref) {
this.pref = pref;
}
//Other overridden methods
}
@Singleton
class AppInteractorB implements InteractorB {
private AppSharedPreferences pref;
@Inject
public AppInteractor(@NonNull AppSharedPreferences pref) {
this.pref = pref;
}
//Other overridden methods
}
现在,InteractorA和InteractorB要在某些其它类注射。 InteractorA和InteractorB实例本身都是singleton,只要它们被注入。但是InteractorA的对象和InteractorB的对象提供了SharedPreferences类的不同实例。所以InteractorA拥有不同的SharedPreferences实例,InteractorB拥有不同的SharedPreferences实例。
有人可以帮助确保InteractorA和InteractorB具有相同的SharedPreferences实例。
感谢。
答
@Module
public class AppModule {
// ...
@Provides
public SharedPreferences providePreferences(){
return new AppSharedPreferences(appContext, prefFile);
}
}
虽然AppSharedPreferences标注有@Singleton
,你调用它自己的构造函数,这意味着匕首不能保证有一个在你的应用程序只有一个SharedPreferences实例。这意味着当您注入SharedPreferences时,您将获得一个新的AppSharedPreferences实例,包括通过InteractorsComponent组件依赖项。
您应该用@Singleton标记providePreferences
,或在AppSharedPreferences上使用@Inject
构造函数,以便Dagger可以管理其@Singleton
行为。
为什么倒票? – Sunny