没有注入构造函数,就无法提供RequestQueue

时间:2018-03-15 14:02:32

标签: android dependency-injection dagger-2

我正在尝试从这篇中篇文章中学习Dagger2并将RequestQueue作为活动级别依赖项传递: https://proandroiddev.com/dagger-2-annotations-binds-contributesandroidinjector-a09e6a57758f 我可以很好地创建应用程序组件,但是我在使用ContributesAndroidInjector时遇到了很多麻烦。 申请类:

public class PokemonApplication extends Application {
    private static AppComponent appComponent;
    public static AppComponent getAppComponent(){
        return appComponent;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appComponent=buildMyComponent();
    }

    private AppComponent buildMyComponent() {
        return DaggerAppComponent.builder().appmod(this).build();
    }


}

的AppModule:

 @Module
    public abstract   class AppModule {
        @ContributesAndroidInjector(modules = VolleyModule.class)
        abstract MainActivity mainActivity();


        @Provides
        @Singleton
         static SharedPreferences providePreferences(Application application) {
            return application.getSharedPreferences("data", Context.MODE_PRIVATE);
        }
        @Provides
        @Singleton
        static Context getContext(Application application){
            return application.getApplicationContext();
        }

    }

AppComponent:

@Singleton
@Component(modules = {RetrofitModule.class,AppModule.class})
public interface AppComponent {

    void inject(MainActivity mainActivity); //Error here.

    @Component.Builder
    interface Builder
    {
        AppComponent build();
        @BindsInstance Builder appmod(Application application);


    }

}

VolleyModule:

@Module
public abstract class VolleyModule {


    @Provides
    static RequestQueue getRequestQueue(Context context) {
        return Volley.newRequestQueue(context);
    }
}

MainActivity:

 @Inject
    RequestQueue requestQueue;
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PokemonApplication.getAppComponent().inject(this);

1 个答案:

答案 0 :(得分:0)

VolleyModule也必须在Component

的模块列表中声明
  @Singleton
  @Component(modules = {RetrofitModule.class,AppModule.class, VolleyModule.class})