magento2 – Argument X __construct() must implement interface xx

I’ve created a Console command that imports customers from a json file. It works fine, Magento generates the classes correctly when executing setup:di:compile.

But I get constantly the error:

Type Error occurred when creating object: BrildorMigrationConsoleCommandImportCustomersInterceptor, Argument 4 passed to BrildorMigrationConsoleCommandImportCustomers::__construct() must implement interface MagentoCustomerApiAddressRepositoryInterface, ins  
tance of MagentoCustomerModelResourceModelCustomerRepositoryInterceptor given, called in /var/www/html/generated/code/Brildor/Migration/Console/Command/ImportCustomers/Interceptor.php on line 14

I’m using Magento 2.4.1 and PHP 7.4.

I’m obliged to execute bin/magento setup:di:compile everytime to get rid of this error. My module is very simple:

etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="MagentoCatalogModelCategoryDataProvider">
        <plugin name="categoryCustomAttributes" type="ModuleMigrationPluginModelCategoryDataProvider" sortOrder="1" disabled="false"/>
    </type>
    <type name="MagentoFrameworkConsoleCommandListInterface">
        <arguments>
            <argument name="commands" xsi:type="array">
                <item name="import_customers" xsi:type="object">ModuleMigrationConsoleCommandImportCustomers</item>
            </argument>
        </arguments>
    </type>
</config>

Console/Command/ImportCustomers.php

<?php
/**
 * Copyright ©  All rights reserved.
 * See COPYING.txt for license details.
 */
declare(strict_types=1);

namespace ModuleMigrationConsoleCommand;

use JsonMachineJsonMachine;
use MagentoCustomerApiAccountManagementInterface;
use MagentoCustomerApiCustomerRepositoryInterface;
use MagentoCustomerApiDataCustomerInterface;
use MagentoCustomerApiDataCustomerInterfaceFactory;
use MagentoCustomerApiDataAddressInterfaceFactory;
use MagentoCustomerApiDataAddressExtensionFactory;
use MagentoFrameworkApiSearchCriteriaBuilder;
use MagentoCustomerModelCustomer;
use MagentoCustomerApiAddressRepositoryInterface;
use MagentoFrameworkApiDataObjectHelper;
use MagentoFrameworkAppResourceConnection;
use MagentoFrameworkExceptionInputException;
use MagentoFrameworkExceptionLocalizedException;
use MagentoFrameworkExceptionNoSuchEntityException;
use MagentoFrameworkExceptionStateInputMismatchException;
use MagentoFrameworkFilesystemDirectoryList;
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputInterface;
use SymfonyComponentConsoleInputInputOption;
use SymfonyComponentConsoleOutputOutputInterface;

class ImportCustomers extends Command
{
    const FILE_OPTION = "file";
    private DirectoryList $directoryList;
    protected CustomerInterfaceFactory $customerFactory;
    protected CustomerRepositoryInterface $customerRepository;
    protected AddressInterfaceFactory $customerAddressFactory;
    protected AddressExtensionFactory $customerAddressExtensionFactory;
    protected AddressRepositoryInterface $customerAddressRepository;
    private DataObjectHelper $dataObjectHelper;
    private AccountManagementInterface $accountManagement;
    private int $count;
    private array $referers = (
        'Google' => '3806',
        'Youtube' => '3807',
        'Facebook' => '3809',
        'Instagram' => '3810',
        'C!Print' => '3812',
        'Recomendación' => '3811'
    );
    private array $allowedCountries = (
        'AL', 'AD', 'AM', 'AT', 'AZ', 'BY', 'BE', 'BA', 'BG', 'CA', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'GE', 'DE', 'GI', 'GR', 'HU',
        'IS', 'IE', 'IT', 'LV', 'LI', 'LT', 'LU', 'MT', 'MD', 'MC', 'ME', 'NL', 'MK', 'NO', 'PL', 'PT', 'RO', 'RU', 'RS', 'SK', 'SI', 'ES',
        'SE', 'CH', 'TR', 'UA', 'GB', 'US', 'VA',
    );
    private SearchCriteriaBuilder $searchCriteriaBuilder;
    /**
     * @var Customer
     */
    private Customer $customer;
    private int $countcompare;
    /**
     * @var ResourceConnection
     */
    private ResourceConnection $resource;

    /**
     * ImportProducts constructor.
     * @param DirectoryList $directoryList
     * @param ResourceConnection $resource
     * @param CustomerInterfaceFactory $customerFactory
     * @param AddressRepositoryInterface $customerAddressRepository
     * @param AddressExtensionFactory $customerAddressExtensionFactory
     * @param CustomerRepositoryInterface $customerRepository
     * @param AddressInterfaceFactory $customerAddressFactory
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param DataObjectHelper $dataObjectHelper
     * @param AccountManagementInterface $accountManagement
     * @param Customer $customer
     */
    public function __construct(
        DirectoryList $directoryList,
        ResourceConnection $resource,
        CustomerInterfaceFactory $customerFactory,
        AddressRepositoryInterface $customerAddressRepository,
        AddressExtensionFactory $customerAddressExtensionFactory,
        CustomerRepositoryInterface $customerRepository,
        AddressInterfaceFactory $customerAddressFactory,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        DataObjectHelper $dataObjectHelper,
        AccountManagementInterface $accountManagement,
        Customer $customer
    )
    {
        $this->directoryList = $directoryList;
        $this->resource = $resource;
        $this->count = 0;
        $this->countcompare = 0;
        $this->customerFactory = $customerFactory;
        $this->customerAddressFactory = $customerAddressFactory;
        $this->customerAddressExtensionFactory = $customerAddressExtensionFactory;
        $this->customerAddressRepository = $customerAddressRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->customerRepository = $customerRepository;
        $this->dataObjectHelper = $dataObjectHelper;
        $this->accountManagement = $accountManagement;
        $this->customer = $customer;

        parent::__construct();
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    )
    {
        $file = $input->getOption(self::FILE_OPTION);
        $dir = $this->directoryList->getRoot();

        if ($file) {
            $customersData = JsonMachine::fromFile($dir . '/' . $file);

            if ($customersData) {
                $this->importCustomers($customersData);
            }
        } else {
            echo 'File is missing: please introduce a file parameter with -f' . "n";
        }
    }

    public function deleteCustomers($customersData)
    {
        $searchCriteria = $this->searchCriteriaBuilder->create();
        $result = $this->customerRepository->getList($searchCriteria);

        if (count($result->getItems()) > 0) {
            foreach ($result->getItems() as $customer) {
                $customerId = $customer->getId();
                $this->customerRepository->deleteById($customerId);
            }
        }
    }

    public function importCustomers($customersData)
    {
        foreach ($customersData as $customerData) {
            $this->count++;
            $this->createCustomerAccount($customerData);
        }
    }

    public function createCustomerAccount($customerData)
    {
        /*if ($customerData('email') != 'laranxocreacions@gmail.com') {
            return;
        }*/
        try {
            $customer = $this->customerRepository->get($customerData('email'));
            echo 'Customer with email: ' . $customerData('email') . " exists. Updating and recreating addresses...n";
        } catch (NoSuchEntityException $e) {
            echo 'There is no customer with email: ' . $customerData('email') . "n";
            $customer = $this->customerFactory->create();

            echo 'Name and email: ' . $customerData('firstname') . ' -- ' . $customerData('email') . "n";

            //$customer->setData(CustomerInterface::ID, $customerData('old_id'));
            $customer->setData(CustomerInterface::EMAIL, $customerData('email'));
            $customer->setData(CustomerInterface::WEBSITE_ID, $customerData('website_id'));
            $customer->setData(CustomerInterface::STORE_ID, $customerData('sendemail_store_id'));
            $customer->setData(CustomerInterface::FIRSTNAME, $customerData('firstname'));
            $customer->setData(CustomerInterface::LASTNAME, $customerData('lastname'));
            $customer->setData(CustomerInterface::GROUP_ID, 1);
            $customer->setData(CustomerInterface::CREATED_AT, $customerData('created_at'));
            $customer->setData(CustomerInterface::UPDATED_AT, $customerData('updated_at'));
            $customer->setData(CustomerInterface::TAXVAT, $customerData('taxvat'));

            $customer->setCustomAttribute('old_id', $customerData('old_id'));
            $customAttributesData = (
                'old_id' => $customerData('old_id'),
                'company' => $customerData('empresa'),
                'account_manager' => $customerData('account_manager'),
                'business_info' => $customerData('info_negocio'),
                'job_description' => $customerData('cargo'),
                'tax_exempt' => $customerData('free_tax'),
                'admin' => $customerData('administrador'),
                'referer' => ($customerData('where_meet_us') != '') ? $this->referers($customerData('where_meet_us')) : '',
                'website' => $customerData('webpage')
            );

            foreach ($customAttributesData as $code => $customAttributesDatum) {
                $customer->setCustomAttribute($code, $customAttributesDatum);
            }

            try {
                $customer = $this->customerRepository->save($customer);
            } catch (InputException $e) {
            } catch (InputMismatchException $e) {
            } catch (LocalizedException $e) {
                $customer = $this->customer->setWebsiteId(0)->loadByEmail($customerData('email'));
            }
        } catch (LocalizedException $e) {
            var_dump($e->getMessage());
        }

        // Update Password Hash
        $customerId = $customer->getId();
        $hash = $customerData('password_hash');
        $connection = $this->resource->getConnection(MagentoFrameworkAppResourceConnection::DEFAULT_CONNECTION);
        $connection->query("UPDATE customer_entity SET password_hash = '$hash' WHERE entity_id = '$customerId'");

        // Save customer addresses
        if ($customerData('addresses')) {
            $this->deleteAllCustomerAddresses($customerId);

            $addresses = $this->cleanDuplicatedAddresses($customerData('addresses'));
            foreach ($addresses as $addressData) {
                $this->saveCustomerAddress($addressData, $customerId);
            }
        }
    }

    public function cleanDuplicatedAddresses($addresses)
    {
        $attributesToCompare = array('vat_id', 'firstname', 'lastname', 'company', 'city', 'region', 'postcode', 'country_id', 'fax', 'region_id', 'street');
        $dontCheck = array();
        foreach ($addresses as $key => $address) {
            //var_dump('Key ' . $key);
            //var_dump($checked);
            $checkForDuplicates = false;
            if (!isset($dontCheck($key))) {
                $checkForDuplicates = true;
            } else {
                if (!$dontCheck($key)) {
                    $checkForDuplicates = true;
                }
            }

            if ($checkForDuplicates) {
                foreach ($addresses as $subkey => $subaddress) {
                    $dontCheck($subkey) = 0;
                    if ($key != $subkey && $subaddress('country_id')) {
                        //var_dump('Subkey: ' . $subkey);
                        $equal = true;
                        foreach ($attributesToCompare as $attributeToCompare) {
                            if (isset($subaddress($attributeToCompare)) && isset($address($attributeToCompare))) {
                                if ($subaddress($attributeToCompare) != $address($attributeToCompare)) {
                                    $equal = false;
                                }
                            }

                            if (isset($subaddress($attributeToCompare)) && !isset($address($attributeToCompare))) {
                                if ($subaddress($attributeToCompare) != '') {
                                    $equal = false;
                                } else {
                                    $equal = true;
                                }
                            }

                            if (isset($address($attributeToCompare)) && !isset($subaddress($attributeToCompare))) {
                                if ($address($attributeToCompare) != '') {
                                    $equal = false;
                                } else {
                                    $equal = true;
                                }
                            }
                        }

                        if ($equal) {
                            $dontCheck($subkey) = 1;
                            //echo 'Address are equal' . "n";
                            if (isset($subaddress('default_shipping'))) {
                                $addresses($key)('default_shipping') = '1';
                            }
                            if (isset($subaddress('default_billing'))) {
                                $addresses($key)('default_billing') = '1';
                            }
                            unset($addresses($subkey));
                            continue;
                        }
                    }
                }
            }
        }

        return $addresses;
    }

    public function deleteAllCustomerAddresses($customerId)
    {
        $searchCriteria = $this->searchCriteriaBuilder->addFilter('parent_id', $customerId, 'eq')->create();
        $result = $this->customerAddressRepository->getList($searchCriteria);

        foreach ($result->getItems() as $address) {
            $this->customerAddressRepository->deleteById($address->getId());
        }
    }

    public function saveCustomerAddress($addressData, $customerId)
    {
        if (isset($addressData('country_id')) && isset($addressData('firstname')) && isset($addressData('city')) && isset($addressData('street'))) {
            if (in_array($addressData('country_id'), $this->allowedCountries)) {
                $address = $this->customerAddressFactory->create();
                if (!isset($addressData('telephone'))) {
                    $addressData('telephone') = '';
                }
                $addressData('street_array') = explode("n", $addressData('street'));

                $telephone = $addressData('telephone');
                if (isset($addressData('fax'))) {
                    if ($addressData('fax') != '') {
                        $telephone = $addressData('fax');
                    }
                }

                $vatId = '';
                if (isset($addressData('vat_id'))) {
                    $vatId = $addressData('vat_id');
                }

                if ($addressData('country_id') == 'PT' && isset($addressData('region'))) {
                    $region = $addressData('region');
                    $connection = $this->resource->getConnection(MagentoFrameworkAppResourceConnection::DEFAULT_CONNECTION);
                    $addressData('region_id') = $connection->fetchOne("SELECT region_id FROM directory_country_region WHERE code = '$region'");
                }

                $address->setCustomerId($customerId)
                    ->setFirstname($addressData('firstname'))
                    ->setLastname($addressData('lastname'))
                    ->setCountryId($addressData('country_id'))
                    ->setPostcode($addressData('postcode'))
                    ->setCity($addressData('city'))
                    ->setTelephone($telephone)
                    ->setVatId($vatId)
                    ->setCustomAttribute('landline', $addressData('telephone'))
                    ->setStreet($addressData('street_array'));

                if (isset($addressData('default_billing'))) {
                    $address->setIsDefaultBilling($addressData('default_billing'));
                }

                if (isset($addressData('region_id')) && $addressData('country_id') == 'ES') {
                    $address->setRegionId($addressData('region_id'));
                }

                if (isset($addressData('default_shipping'))) {
                    $address->setIsDefaultShipping($addressData('default_shipping'));
                }

                try {
                    $this->customerAddressRepository->save($address);
                } catch (LocalizedException $e) {
                    var_dump($e->getMessage());
                    echo 'Trying again...' . "n";
                    sleep(5);
                    $this->saveCustomerAddress($addressData, $customerId);
                }
            }
        }
    }

    /**
     * Fill in customer entity using array of customer data and additional customer data.
     *
     * @param array $customerData
     * @param array $additionalCustomerData
     * @param CustomerInterface|null $customerEntity
     * @return CustomerInterface
     */
    private function populateCustomerEntity(
        array $customerData,
        ?CustomerInterface $customerEntity = null
    ): CustomerInterface
    {
        $customerEntity = $customerEntity ?? $this->customerFactory->create();
        $this->dataObjectHelper->populateWithArray(
            $customerEntity,
            $customerData,
            CustomerInterface::class
        );

        return $customerEntity;
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName("custom_migration:import_customers");
        $this->setDescription("Import Customers from a json file");
        $this->setDefinition((
            new InputOption(self::FILE_OPTION, "-f", InputOption::VALUE_REQUIRED, "File name")
        ));
        parent::configure();
    }
}

Any idea why this error happens again and again?