我正在尝试使用Dagger 2来实例化Retrofit界面。 CloudContactDataStore
类注入RestClient
并调用其方法。
当我实例化CloudContactDataStore
对象时,其RestClient
属性的值为null
。
public class CloudContactDataStore implements ContactDataStore {
@Inject RestClient restClient;
public CloudContactDataStore() {
this.initializeInjector();
}
private void initializeInjector() {
DaggerApiComponent.builder()
.apiModule(new ApiModule())
.build()
.inject(this);
}
@Override
public Observable<ContactEntity> contactLogin(String contactId) {
return this.restClient.contactLogin(contactId); // Here restClient is null!
}
}
以下是我创建Dagger模块和组件的方法:
@Singleton
@Component(modules = ApiModule.class)
public interface ApiComponent {
void inject(ContactDataStore contactDataStore);
}
@Module
public class ApiModule {
@Provides public RestClient provideRestClient(ApiService apiService) {
return new RestClientImpl(apiService);
}
@Provides public ApiService provideApiService(RestAdapter restAdapter) {
return restAdapter.create(ApiService.class);
}
@Provides public RestAdapter provideRestAdapter() {
return RestApiAdapter.getInstance();
}
}
现在,RestClient
类及其实现:
public interface RestClient {
Observable<ContactEntity> contactLogin(String contactId);
}
public class RestClientImpl implements RestClient {
ApiService apiService;
@Inject
public RestClientImpl(ApiService apiService) {
this.apiService = apiService;
}
@Override
public Observable<ContactEntity> contactLogin(String contactId) {
return apiService.login(contactId, "xxx-xxx-xxx");
}
}
ApiService
界面是Retrofit界面:
public interface ApiService {
String API_BASE_URL = "http://192.168.1.2";
@POST("/login")
Observable<ContactEntity> login(@Body String id, @Header("Key") String key);
}
最后,RestApiAdapter
:
public class RestApiAdapter {
private static RestAdapter sharedInstance = null;
public static RestAdapter getInstance() {
if (sharedInstance == null){
sharedInstance = new RestAdapter.Builder()
.setLogLevel(RestAdapter.LogLevel.FULL)
.setEndpoint(ApiService.API_BASE_URL)
.build();
}
return sharedInstance;
}
}
谁能看到我做错了什么?
谢谢!
答案 0 :(得分:1)
这与Why Dagger inject is not working but component.getObject yes和同一解决方案中的问题相同。也就是说,您需要将inject(ContactDataStore)
方法更改为inject(CloudContactDataStore)
,以便它可以看到需要注入的字段,或者您需要在ContactDataStore
中添加一个允许您注入方法的方法自己。