我是Dagger的新手,我正在尝试实现一个继承自正在进行注入的类的类。当我在MainActivity中注入一个组件并从BaseActivity继承它时,事情就破裂了。
我的AppComponentClass:
@Singleton
@Component(modules = {NetworkModule.class, ApplicationModule.class,
AndroidModule.class})
public interface AppComponent {
void inject (BaseActivity baseActivity);
void inject (MainActivity mainActivity);
}
}
我的ActivityModule类:
@Module
public class ActivityModule {
private Activity activity;
public ActivityModule(Activity activity) {
this.activity = activity;
}
@PerActivity
@Provides
@ActivityContext
public Context provideContext() {
return activity;
}
}
我的ApplicationModule类:
@Module
public class ApplicationModule {
private Application application;
public ApplicationModule(Application application) {
this.application = application;
}
@Provides
@Singleton
@ApplicationContext
public Context provideContext() {
return this.application;
}
@Provides
@Singleton
public FCMTokenHelper provideFCMTokenHelper(Context context, ApiService apiService) {
UserRepoImpl userRepo = new UserRepoImpl(apiService);
return new FCMTokenHelper(context, context.getClass().getSimpleName(), userRepo);
}
@Provides
@Singleton
public UserRepoContract providerUserRepo(ApiService apiService) {
return new UserRepoImpl(apiService);
}
}
我的两个班级(都在kotlin)
class MainActivity : BaseActivity() {
}
abstract class BaseActivity : AppCompatActivity(), GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ActivityCompat.OnRequestPermissionsResultCallback, LocationListener {
@Inject
lateinit var userRepo: UserRepoContract
@Inject
internal var tokenHelper: FCMTokenHelper? = null
}
错误:
错误:(51,10)错误:。如果没有@Annex-annotated方法,则无法提供.BaseActivity。在AppComponent.inject(baseActivity)注入BaseActivity 错误:(75,10)错误:如果没有@Inject构造函数或@ Provide-annotated方法,则无法提供MainActivity。 MainActivity注入.AppComponent.inject(mainActivity)
使用Dagger 2 ver 2.9 Android Studio 3.0 Kotlin和Java
答案 0 :(得分:1)
我的问题在这里:
@Inject
internal var tokenHelper: FCMTokenHelper? = null
将其更改为:
@Inject
lateinit var tokenHelper: FCMTokenHelper
修正了问题。请参阅一个很好的解释here.