简体   繁体   中英

Dagger2 Android Depedency injection java

i'm new to dagger2. I'm trying to create an 'ActivityComponent' which will retrieves all information from my activity (ex: context...), and an another component in which i'm trying to inject the 'Activity component' (in the code below, it's the CheckErrorsModel class).

@Singleton
public class CheckErrorsModel {

private Context context;

@Inject
public CheckErrorsModel(MainActivityComponent mainActivityComponent) {
    this.context = mainActivityComponent.getContext();
}

public void test() {
    Log.d("test", "test lancé ");
}
}

The Interface component class:

  @Singleton
  @Component()
  public interface CheckErrorsModelDi {
      CheckErrorsModel getCheckErrorsModel();
      MainActivityComponent getApplicationComponent();
  }

And everything related to the Application context class:

@Component(modules = {MainActivityModule.class})
@Singleton
public interface MainActivityComponent {
   Context getContext();
   void inject(MainActivity mainActivity);
}

the module class:

@Module
public class MainActivityModule {
    private final Context context;

    public MainActivityModule(Context context) {
       this.context = context;
    }

    @Provides
    @Singleton
    Context provideContext(){
        return context;
    }
}

But once i try to build the app: i got some errors:

.MainActivityComponent cannot be provided without an @Provides-annotated method MainActivityComponent getApplicationComponent();

MainActivityComponent cannot be provided without an @Provides-annotated method. CheckErrorsModel getCheckErrorsModel()

I think this is because your CheckErrorsModelDi don't have any module. And Scope (like @Singleton) should always be on Module method and the component

And this should be a subComponent of MainActivityComponent

Alors you inject Method seems à bit strange.

You should use à builder instead see bindings instance

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM