我已經創建了NetComponent和NetModule,用於初始化網絡通信所需的所有庫。如何在Dagger 2中使用多個依賴關係?
這裏是NetComponent代碼:
@Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
Retrofit retrofit();
}
我已經initalised是NetComponent內部應用程序類。
public class App extends Application {
private NetComponent mNetComponent;
@Override
public void onCreate() {
super.onCreate();
mNetComponent = DaggerNetComponent.builder()
.appModule(new AppModule(this))
.netModule(new NetModule("mock.com"))
.build();
}
public NetComponent getNetComponent() {
return mNetComponent;
}
}
現在我想在我的應用程序中使用SharedPreferences,所以我創建了SharedPreferencesModule和Component類。
@Module
public class SharedPreferenceModule {
Application mApplication;
public SharedPreferenceModule(Application mApplication) {
this.mApplication = mApplication;
}
@Provides
@Singleton
Application providesApplication() {
return mApplication;
}
@Provides
@Singleton
SharedPreferences providesSharedPreferences(Application application) {
return PreferenceManager.getDefaultSharedPreferences(application);
}
}
下面是從SharedPreferencesComponent代碼:
@Singleton
@Component(modules = {SharedPreferenceModule.class})
public interface SharedPreferenceComponent {
SharedPreferences getSharedPreference();
}
我想用我的LoginAccountFragment內類。 LoginAccountFragment類有它自己的模塊和組件。
@Module
public class LoginAccountModule {
private LoginAccountView view;
public LoginAccountModule(LoginAccountView view){
this.view = view;
}
@Provides
@FragmentScoped
LoginAccountView providesLoginAccountView(){
return view;
}
@Provides
@FragmentScoped
LoginAccountPresenter providesLoginAccountPresenter(LoginAccountPresenterImpl presenter){
return presenter;
}
}
@FragmentScoped
@Component(dependencies = {NetComponent.class}, modules = LoginAccountModule.class)
public interface LoginAccountComponent {
void inject(LoginAccountFragment fragment);
}
我該如何在LoginAccountFragment中注入SharedPreferences?
不應該有'SharedPreferenceComponent'。你的'NetComponent'應該被稱爲'ApplicationComponent'。 – EpicPandaForce
用一些至少僞代碼發佈答案,我會接受它。 – Zookey