我是dagger的新手,我已经定义了我的应用程序组件
@Singleton
@Component(modules = {ApplicationModule.class})
public interface ApplicationComponent {
void inject(BaseActivity activity);
Context context();
}
这是我的ApplicationModule
@Module
public class ApplicationModule {
public TipoApplication application;
public ApplicationModule(TipoApplication application) {
this.application = application;
}
@Singleton
@Provides
public Context provideContext(){return application.getApplicationContext();}
@Singleton
@Provides
public SharedPreferences provideSharedPreferences(Context context){
return PreferenceManager.getDefaultSharedPreferences(context);
}
@Singleton
@Provides
public Gson provideGson(){
return new Gson();
}
@Singleton
@Provides
public SharedPrefsManager provideSharedPrefsManager(SharedPreferences sharedPreferences, Gson gson){
return new SharedPrefsManager(sharedPreferences, gson);
}
}
我已经创建了一个依赖的组件LocationProviderComponent
@LocationScope
@Component(dependencies = {ApplicationComponent.class},modules = {LocationProviderModule.class})
public interface LocationProviderComponent {
void inject(LocationRepository locationRepository);
}
最后是我的LocationProviderModule
@Module
public class LocationProviderModule {
@Singleton
@Provides
FusedLocationProviderClient provideFusedLocationProviderClient(Context context) {
return LocationServices.getFusedLocationProviderClient(context);
}
@Singleton
@Provides
LocationRequest provideLocationRequest() {
return new LocationRequest()
.setInterval(5000)
.setFastestInterval(60000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
@Singleton
@Provides
LocationSettingsRequest provideLocationSettingRequest(LocationRequest mLocationRequest) {
return new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest).build();
}
}
构建时出现2个错误。
第一个找不到符号类DaggerApplicationComponent 第二
LocationProviderComponent scoped with LocationScope may not reference bindings with different scopes:
@Singleton @Provides FusedLocationProviderClient LocationProviderModule.provideFusedLocationProviderClient(android.content.Context)
@Singleton @Provides LocationRequest .module.LocationProviderModule.provideLocationRequest()
请告诉我我在做错什么。
答案 0 :(得分:2)
任何模块的@Provides
方法都只能具有与其所属组件相同的作用域。了解更多here。
在您的情况下,LocationProviderModule
是LocationProviderComponent
的一部分,而@LocationScope
的范围是@Singleton
,而该模块中的provider方法使用@Singleton @Provides FusedLocationProviderClient LocationProviderModule.provideFusedLocationProviderClient(android.content.Context)
@Singleton @Provides LocationRequest.module.LocationProviderModule.provideLocationRequest()
范围。这正是Dagger抱怨的:
由LocationScope范围限定的LocationProviderComponent可能无法引用 具有不同范围的绑定
它也指出了问题所在:
@Singleton
您无需使用@LocationScope
,而只需要在LocationProviderModule
中使用node_modules/react-scripts/scripts/utils/verifyTypeScriptSetup.js
。