我已经和dagger2合作了一段时间.我为每个Activity/Fragment创建一个自己的组件/模块感到困惑.请帮我澄清一下:
例如,我们有一个应用程序,该应用程序有大约50个屏幕.我们将实现遵循MVP模式的代码和用于DI的Dagger2.假设我们有50个活动和50个演示者.
在我看来,通常我们应该像这样组织代码:
创建一个AppComponent和AppModule,它将提供应用程序打开时将使用的所有对象.
@Module
public class AppModule {
private final MyApplicationClass application;
public AppModule(MyApplicationClass application) {
this.application = application;
}
@Provides
@Singleton
Context provideApplicationContext() {
return this.application;
}
//... and many other providers
}
@Singleton
@Component( modules = { AppModule.class } )
public interface AppComponent {
Context getAppContext();
Activity1Component plus(Activity1Module module);
Activity2Component plus(Activity2Module module);
//... plus 48 methods for 48 other activities. Suppose that we don't have any other Scope (like UserScope after user login, ....)
}
Run Code Online (Sandbox Code Playgroud)创建ActivityScope:
@Scope …Run Code Online (Sandbox Code Playgroud)