我正在努力与匕首2,以了解我如何根据我的需要传递一个或另一个上下文. - 首先我有一个ApplicationModule注释@Singleton,因为它提供了高级对象,如webservice对象,模型......,通常那些对象传递给ApplicationContext(因为y需要在整个Application生命周期中生存)
@Singleton
@dagger.Component(modules = {
AppModule.class
})
public interface AppComponent {
void inject(MyApp application);
Model model();
Context context();<--- should provide the application Context for the Object above (model)
...
Run Code Online (Sandbox Code Playgroud)
实现看起来像那样
@dagger.Module
public class AppModule {
private final Application app;
public ApplModule(Application app) {
this.app = app;
}
@Provides
@Singleton
Model provideModel(Bus bus) {
return new Model(bus);
}
@Provides
@Singleton
Context provideApplicationContext() {
return app.getApplicationContext();
}
...
Run Code Online (Sandbox Code Playgroud)
其次我有一个活动范围组件,我提供当前活动和需要上下文的不同视图.
@ActivityScope
@Component(
dependencies = AppComponent.class
, modules = {ActivityModule.class}
)
public …Run Code Online (Sandbox Code Playgroud)dagger-2 ×1