所以我正在学习 Dagger 2,但有一件事我不太明白。 所以我知道在组件中您需要指定可用于注入(inject)的 Activity :
Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
void inject(MainActivity activity);
}
首先,为什么我需要指定这一点? (我从来没有使用过变量 Activity )。
但主要问题是,假设我有 10 个不同的 Activity 或 fragment ,我需要将它们全部列在这里吗?这是正确的方法吗?或者我们可以注入(inject)到应用程序中吗?如果我想在整个应用程序中使用 NetComponent,正确的做法是什么?
谢谢
最佳答案
如果您的每一项 Activity 都有一个供应组件,那么是的。您必须为每一个编写 inject()
方法。
另请注意,您不能使用注入(inject)到基类中,因为它会产生以下错误:https://github.com/google/dagger/issues/214
好:
@Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
void inject(MainActivity activity);
void inject(SplashActivity activity);
void inject(AnotherActivity activity);
}
坏:
@Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
void inject(BaseActivity activity);
}
此外,如果您不想注入(inject),而只想获取 API 服务等,则不能注入(inject),但可以使用:
@Singleton
@Component(modules={AppModule.class, NetModule.class})
public interface NetComponent {
SomeNetworkOrApiClass getNetworking();
}
并且只需在需要时从组件获取网络即可。
尝试阅读这些有用的文章:
https://github.com/codepath/android_guides/wiki/Dependency-Injection-with-Dagger-2
https://github.com/konmik/konmik.github.io/wiki/Snorkeling-with-Dagger-2
关于android - 针对不同 Activity 的 Dagger 注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36846093/