我正在按照一些例子来处理dagger2。在这里,我使用HomeFragmentComponent上的依赖项来提供来自另一个范围的上下文的引用,但它不起作用。
ContextModule
@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);
}
Home Fragment Module:
@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);
}
}
HomeFragmentComponent:
@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注入
答案 0 :(得分:0)
您应该将ContextModule
包含为HomeFragmentModule
依赖关系,以便Dagger2能够向context
提供DatabaseHelper
@Module(includes = ContextModule.class)
public class HomeFragmentModule {
// Your stuff here
}