我已经创建了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