背景
我正在将我的应用程序转换为MVP架构,并发现Dagger 2在需要时注入依赖项非常有用.我的应用程序需要与两个web apis(我自己和第三方api)进行通信.有时可能会向我自己的api和第三方api发出请求.我正在使用Retrofit与这些api进行通信并使用GSON进行序列化/反序列化.
我以前做过什么
我创建了两个Retrofit RestAdapter并使用Service Locator模式在需要时获取它们.旨在用于我自己的api的RestAdapter包括带有一些自定义TypeAdapter的GSONConverter,因为我不想在应用程序中对我的响应进行1:1 JSON反序列化.另一个RestAdapter用于第三方api,并使用另一个具有特定字段命名策略的GSONConverter.
问题
我正在尝试使用DI而不是Service Locator来获取我的RestAdapter(以及API接口).我的NetModule类设置如下
@Module
public class NetModule {
private static final String MY_API_URL = "my_api_url";
private static final String THIRD_PARTY_API_URL = "third_party_api_url";
@Provides
@Singleton
Cache provideOkHttpCache(Application application) {
int cacheSize = 10 * 1024 * 1024; // 10 MiB
return new Cache(application.getCacheDir(), cacheSize);
}
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Cache cache) {
OkHttpClient client = new OkHttpClient();
client.setCache(cache);
return client;
}
@Provides
@Singleton
TypeAdapter<MyClass> provideMyAPITypeAdapter() {
return new TypeAdapter<MyClass>() {
// implementation ignored …Run Code Online (Sandbox Code Playgroud)