0

我正在按照一些示例来研究 dagger2。在这里,我使用对 HomeFragmentComponent 的依赖项来提供来自另一个范围的上下文引用,但它不起作用。

上下文模块

    @Module
    public class ContextModule {
          private final Context context;

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

         @Provides
         @ShikshyaScope
         public Context context(){
              return context;
         }
    }

网络模块:

@Module(includes = ContextModule.class)
public class NetworkModule {

      @Provides
      @ShikshyaScope
      public File file(Context context){
           File cacheFile = new File(context.getCacheDir(),"okhttp_cache");
           cacheFile.mkdirs();
           return cacheFile;
 }

ShikshyaApplicationComponent:

  @ShikshyaScope
  @Component(modules = {NetworkModule.class, PicassoModule.class, StorageModule.class})
  public interface ShikshyaApplicationComponent {
       void injectShikshyaApplication(ShikshyaBusApplication shikshyaBusApplication);
   }

家庭片段模块:

@Module
public class HomeFragmentModule {

public final HomeFragment homeFragment;

public HomeFragmentModule(HomeFragment homeFragment) {
    this.homeFragment = homeFragment;
}

@Provides
@HomeFragmentScope
public HomeFragment homeFragment(){
    return homeFragment;
}

@Provides
@HomeFragmentScope
public HomeFragmentView homeFragmentView(HomeFragment homeFragment){
    return (HomeFragmentView)homeFragment;
}
@Provides
@HomeFragmentScope
public HomeFragmentPresenter homeFragmentPresenter(HomeFragmentView homeFragmentView,MetaDatabaseRepo metaDatabaseRepo){
    return new HomeFragmentPresenter(homeFragmentView,metaDatabaseRepo);
}


@Provides
@HomeFragmentScope
public DatabaseHelper databaseHelper(Context context){
    return OpenHelperManager.getHelper(context,DatabaseHelper.class);
}

}

HomeFragment组件:

    @HomeFragmentScope
    @Component(modules = HomeFragmentModule.class,dependencies =ShikshyaApplicationComponent.class)
     public interface HomeFragmentComponent {

     void injectHomeFragment(HomeFragment homeFragment);
     }

现在我得到错误

error: android.content.Context cannot be provided without an @Provides-annotated method.
android.content.Context is injected at com.bihani.shikshyabus.di.module.HomeFragmentModule.databaseHelper(context)

com.bihani.shikshyabus.database.DatabaseHelper 被注入

4

1 回答 1

0

您应该包含ContextModule作为HomeFragmentModule依赖项,以便 Dagger2 能够提供contextDatabaseHelper

@Module(includes = ContextModule.class)
public class HomeFragmentModule {
    // Your stuff here
}
于 2018-06-06T10:29:32.543 回答