У меня есть следующая архитектура Dagger2 в моем приложении:
-- AppComponent (@PerApplication)
-- UserComponent (@PerUser)
-- ActivityComponent (@PerActivity)
-- ChatComponent (@PerActivity) <-- 1
Где: AppComponent:
@PerApplication
@Component(modules = {ApplicationModule.class, StorageModule.class, NetworkModule.class})
public interface ApplicationComponent {
UserComponent plus(UserModule userComponent);
//Exposed to sub-graphs.
Context application();
}
Пользовательский компонент:
@PerUser
@Subcomponent(modules = {UserModule.class, RosterModule.class})
public interface UserComponent {
ActivityComponent plus(ActivityModule activityModule);
User getMe();
UserRepository userRepository();
}
Компонент Активности:
@PerActivity
@Subcomponent(modules = ActivityModule.class)
public interface ActivityComponent {
ChatComponent plus(ChatModule chatComponent);
//Exposed to sub-graphs.
Context context();
}
ЧатКомпонент:
@PerActivity
@Subcomponent(modules = {ChatModule.class})
public interface ChatComponent {
void inject(ChatListFragment chatListFragment);
void inject(ConversationFragment conversationFragment);
void inject(NewConversationFragment newConversationFragment);
void inject(CloudFilesFragment cloudFilesFragment);
void inject(ChatActivity chatActivity);
void inject(ConversationActivity conversationActivity);
void inject(NewConversationActivity newConversationActivity);
void inject(NewGroupActivity newGroupActivity);
void inject(NewGroupFragment newGroupFragment);
}
Я столкнулся с 2 проблемами:
Во-первых, как я могу внедрить разные Context
в свои классы? Либо приложение, либо активность ??
И во-вторых, я столкнулся со странной проблемой при попытке скомпилировать свой код, ошибка:
Ошибка: (23, 10) ошибка: br.com.animaeducacao.ulife.domain.interactor.UseCase не может быть предоставлен без аннотированного метода @Provides. br.com.animaeducacao.ulife.presentation.view.fragment.ChatListFragment.chatListPresenter [введенное поле типа: br.com.animaeducacao.ulife.presentation.presenter.ChatListPresenter chatListPresenter] br.com.animaeducacao.ulife.presentation.presenter. ChatListPresenter.(br.com.animaeducacao.ulife.domain.interactor.UseCase chatDialogsUseCase, br.com.animaeducacao.ulife.domain.interactor.UseCase советаUserPresence, android.content.Context контекст) [параметр: @javax.inject.Named( "getChatDialogs") br.com.animaeducacao.ulife.domain.interactor.UseCase chatDialogsUseCase]
Мой ChatListFragment:
@PerActivity
public class ChatListFragment extends BaseFragment implements ChatListView {
@Inject
ChatListPresenter chatListPresenter;
...
//called onActivityCreated()
private void initialize() {
this.getComponent(ChatComponent.class).inject(this);
}
Базовый фрагмент:
protected <C> C getComponent(Class<C> componentType) {
return componentType.cast(((HasComponent<C>)getActivity()).getComponent());
}
Ведущий списка чатов:
@PerActivity
public class ChatListPresenter implements Presenter {
private final UseCase chatDialogsUseCase;
private final UseCase adviceUserPresence;
private final Context context;
private ChatListView chatListView;
@Inject
public ChatListPresenter(@Named("getChatDialogs") UseCase chatDialogsUseCase,
@Named("adviceUserPresence") UseCase adviceUserPresence,
Context context) {
this.chatDialogsUseCase = chatDialogsUseCase;
this.adviceUserPresence = adviceUserPresence;
this.context = context;
}
Проблема в том, что в моем классе ChatModule я реализовал все необходимые @Provides
:
@Provides
@PerActivity
@Named("getChatDialogs")
public UseCase provideChatDialogs(@Named("transactionalChatRepository") ChatRepository chatRepository, ThreadExecutor threadExecutor, PostExecutionThread postExecutionThread) {
return new GetUserChatDialogs(chatRepository, threadExecutor, postExecutionThread);
}
Хороший ли это подход? Почему это не компилируется, чего мне здесь не хватает? Извините за длинный пост и спасибо!
context
. Если вам нужна активность, введите активность, если вам нужен контекст, вам, вероятно, следует перейти к контексту приложения. - person David Medenjak   schedule 31.12.2015