Ответ 1
Удалите узлы инъекций из вашего CoreComponent
- теперь у него есть единственная функция подвергать привязке для CoreRepository
к ее зависимым компонентам:
@Singleton
@Component(modules = {CoreModule.class})
public interface CoreComponent {
CoreRepository coreRepository();
}
Создайте ссылку на этот компонент с одним ядром внутри приложения:
public class MyApplication extends Application {
private final CoreComponent coreComponent;
@Override
public void onCreate() {
super.onCreate();
coreComponent = DaggerCoreComponent
.coreModule(new CoreModule())
.build();
}
public static CoreComponent getCoreComponent(Context context) {
return ((MyApplication) context.getApplicationContext()).coreComponent;
}
}
Создайте новый более узкий масштаб:
@Scope
@Retention(RetentionPolicy.RUNTIME) public @interface PerActivity {}
Создайте новый компонент, который отслеживает эту область в полном объеме с местами инъекций, которые вы хотите:
@PerActivity
@Component(dependencies = {CoreComponent.class})
public interface ActivityComponent {
void inject(FooActivity activity);
void inject(BarActivity activity);
}
При доступе к этому компоненту с областью действия в узле внедрения вам необходимо предоставить экземпляр CoreComponent
для строителя. Теперь вы можете ввести в свой Activity
public class FooActivity extends AppCompatActivity {
@Inject
public CoreRepository repo;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
CoreComponent coreComponent = MyApplication.getCoreComponent(this);
DaggerActivityComponent.builder()
.coreComponent(coreComponent)
.build()
.inject(this);
}
}
}