我正在尝试如何处理Android中的dagger 2和干净架构的依赖注入。我想要实现的是当我点击一个按钮时,一条消息将被保存到Firebase数据库。并向用户显示成功消息。当我构建我的项目时,我收到了这个错误:
错误:(10,1)错误:com.example.mvpsample.home.HomeComponent (unscoped)可能不会引用作用域绑定:@Provides @Singleton com.google.firebase.database.FirebaseDatabase com.example.mvpsample.data.DataModule.provideFirebaseDatabase()
这是我的app类:
public class MyApp extends Application {
private static MyApp app;
private HomeComponent homeComponent;
private AuthenticationComponent authenticationComponent;
@Inject
Presenter presenter;
@Override
public void onCreate() {
super.onCreate();
app = this;
homeComponent = DaggerHomeComponent
.builder()
.homeModule(new HomeModule(presenter.getView()))
.build();
}
public HomeComponent getHomeComponent() {
return homeComponent;
}
public static MyApp app() {
return app;
}
}
HomeActivity
public class HomeActivity extends AppCompatActivity implements BaseContract.View {
@Inject
public Presenter presenter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
MyApp
.app()
.getHomeComponent()
.inject(this);
}
@OnClick(R.id.tvHello)
public void clickTvHello() {
presenter.writeStringToDatabase("Hi");
}
@Override
public void showSuccessMessage() {
Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
}
}
HomeModule
@Module
public class HomeModule {
private final BaseContract.View View;
@Inject
public HomeModule(BaseContract.View View) {
this.View = View;
}
@Provides
public BaseContract.View provideView() {
return View;
}
}
HomeComponent
@Component(modules = {HomeModule.class, DataModule.class})
public interface HomeComponent {
void inject(HomeActivity homeActivity);
}
DataModule的
@Module
public class DataModule {
@Provides
@Singleton
public FirebaseDatabase provideFirebaseDatabase() {
return FirebaseDatabase.getInstance();
}
}
BaseContract
public interface BaseContract {
interface View {
void showSuccessMessage();
}
interface Presenter {
View getView();
void writeStringToDatabase(String string);
}
}
演示
public class Presenter implements BaseContract.Presenter {
private final BaseContract.View View;
@Inject
FirebaseDatabase firebaseDatabase;
@Inject
public Presenter(BaseContract.View View) {
this.View = View;
}
@Override
public BaseContract.View getView() {
return View;
}
@Override
public void writeStringToDatabase(String string) {
firebaseDatabase.getReference()
.child("messages")
.push()
.child("value")
.setValue(string).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
getView().showSuccessMessage();
}
});
}
}
我遵循了示例项目和教程,但不明白我在这里做错了什么。不是在寻找工作项目,但我想了解什么是最佳实践,以及如何管理和使用模块和组件。
答案 0 :(得分:4)
问题是当HomeComponent
提供范围内的依赖关系(即DataModule
依赖关系)时,FirebaseDatabase
不是作用域的。
非作用域组件不能依赖作用域提供程序。您必须删除@Singleton
提供商处的provideFirebaseDatabase()
或在@Singleton
上添加HomeComponent
。