Dagger注入不适用于Retrofit

时间:2015-10-02 09:15:36

标签: android dependency-injection retrofit dagger-2

我正在尝试使用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;
    }
}

谁能看到我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

这与Why Dagger inject is not working but component.getObject yes和同一解决方案中的问题相同。也就是说,您需要将inject(ContactDataStore)方法更改为inject(CloudContactDataStore),以便它可以看到需要注入的字段,或者您需要在ContactDataStore中添加一个允许您注入方法的方法自己。