Вам не нужно создавать свой компонент для каждого класса, в который вы хотите внедрить зависимости. Зависимости могут быть предоставлены через конструктор, помеченный @Inject
:
public class PersonsRemoteRepository implements PersonsRepository {
private RestClient restClient;
@Inject
public PersonsRemoteRepository(RestClient restClient) {
this.restClient = restClient;
}
}
И любой другой класс, которому нужен этот репозиторий, может сделать то же самое:
public class AnyOtherClass {
private PersonsRemoteRepository personsRemoteRepository;
@Inject
public AnyOtherClass(PersonsRemoteRepository personsRemoteRepository) {
this.personsRemoteRepository = personsRemoteRepository;
}
Вам нужно только использовать [ 116] для классов, экземпляры которых создаются Android, таких как Приложение, Действия и Фрагменты.
public class MyActivity {
@Inject PersonsRemoteRepository personsRemoteRepository;
@Override
public void onCreate() {
super.onCreate();
CoreApplication.getComponent().inject(this);
}
}
Изменения, необходимые в вашем CoreApplication:
public class CoreApplication extends MultiDexApplication {
private static ProjectApplicationComponent component;
@Inject private RestClient restClient;
@Inject private Picasso picasso;
@Inject private Handler handler;
@Override
public void onCreate() {
super.onCreate();
...
component = DaggerProjectApplicationComponent.builder()
.contextModule(new ContextModule(this))
.networkServiceModule(new NetworkServiceModule(ClientSettings.SERVER_URL))
.build();
component.inject(this);
}
}
Изменения, необходимые в вашем ApplicationComponent:
@ActivitiesScope
@Component(dependencies = ProjectApplicationComponent.class)
public interface ApplicationComponent {
void inject(CoreApplication coreApplication);
void inject(MyActivity myActivity);
}