1 回答
TA贡献1982条经验 获得超2个赞
尽管我不确定如何/为什么会显示您所显示的错误,但是您在@Singleton范围内错误地注册了活动范围的内容。请注意,您发布的错误消息抱怨没有提供ActivityCheckout。如果无法提供您的活动,则可能会找到有关缺少MainActivity的错误消息。
我的直觉是,您的编译中存在多个错误,但您仅发布了最后一个错误,而较早的错误表明您无法将@Singleton绑定安装到@ContributesAndroidInjector默认创建的不受作用域的子组件中。因此,Dagger会忽略该@Provides方法,并且会收到错误消息。
@Provides
@Singleton // BAD: If this is Singleton, it will outlive and leak MainActivity.
// Dagger will complain about mismatched scopes, but it's right:
// It doesn't make sense for ActivityCheckout to be @Singleton.
static ActivityCheckout provideActivityCheckout(
MainActivity activity, Billing billing) {
return ActivityCheckout.forActivity(activity, billing);
}
而是创建一个特定于活动的范围,该范围指示每个活动都有自己的活动。
@Retention(RetentionPolicy.RUNTIME) // Not used at runtime, but JSR-330
@Scope // requires that @Scopes are kept at RUNTIME.
public @interface ActivityScope {} // PerActivity is also a good name.
现在,用它标记@ContributesAndroidInjector,以便您生成的子组件具有该作用域:
@ContributesAndroidInjector(
modules = {MainActivityModule.class, MainActivityFragmentsModule.class})
@ActivityScope
abstract MainActivity contributeMainActivity();
而且您的绑定也是如此,因此它们与您的活动组件的生命周期相匹配:
@Module public class MainActivityModule {
// I'm assuming this is actually activity scoped, but if it's truly singleton,
// leave it @Singleton and move it to AppModule.
@Provides
@ActivityScope
static Billing provideBilling(Context context) {
return new Billing(context);
}
@Provides
@ActivityScope
static ActivityCheckout provideActivityCheckout(
MainActivity activity, Billing billing) {
return ActivityCheckout.forActivity(activity, billing);
}
}
添加回答
举报