我跟随新的Dagger2支持Android实现电影列表示例应用程序,下面是我的用例。
我在演示者内部使用@Inject进行ApiService接口,但是我收到一个错误,我不能使用@Inject字段而不声明提供注释,下面是我的代码
最后是api服务接口
那么如何为MoviesModule提供服务界面才能在演示者中正常工作
错误是
Error:(22, 8) error: [dagger.android.AndroidInjector.inject(T)] sampler.dagger.com.movieslist.data.MoviesApiService cannot be provided without an @Provides-annotated method.
sampler.dagger.com.movieslist.data.MoviesApiService is injected at
sampler.dagger.com.movieslist.movies.MoviePresenter.mApiService
sampler.dagger.com.movieslist.movies.MoviePresenter is injected at
sampler.dagger.com.movieslist.movies.MoviesModule.moviesPresenter(presenter)
sampler.dagger.com.movieslist.movies.MoviesContract.Presenter is injected at
sampler.dagger.com.movieslist.movies.MoviesFragment.mPresenter
dagger.Lazy<sampler.dagger.com.movieslist.movies.MoviesFragment> is injected at
sampler.dagger.com.movieslist.movies.MainActivity.mMoviesFragmentsProvider
sampler.dagger.com.movieslist.movies.MainActivity is injected at
dagger.android.AndroidInjector.inject(arg0)
答案 0 :(得分:1)
一种解决方案可能是:
@Module
public class APIModule {
@Provides
@Singleton
Retrofit provideRetrofit(Gson gson) {
OkHttpClient client = new OkHttpClient.Builder().build();
return new Retrofit.Builder()
.baseUrl("https://stackoverflow.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(client)
.build();
}
@Provides
@Singleton
Gson provideGson() {
return new GsonBuilder().create();
}
@Provides
@Singleton
MoviesApiService provideMoviesApiService(Retrofit retrofit) {
return retrofit.create(MoviesApiService.class);
}
}
在MoviePresenter
中,使用构造函数注入比使用字段注入更好:
private MoviesApiService mApiService;
@Inject
public MoviePresenter(MoviesApiService apiService) {
mApiService = apiService;
}
答案 1 :(得分:-2)
MoviApiService是一个接口,你不能注入接口。您需要创建一个provides
方法来提供改造服务。
MoviApiService提供MoiApiService(改造改造){ retrofit.create(MoviApiService.class); }