Magento – Magento 2: controller preference not working after setup:di:compile

dependency-injectionmagento2overridespreferencesetup-di-compile

I need to rewrite a couple of adminhtml controllers in Magento 2. I am using preference and my configuration in etc/di.xml file looks like this:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">

    <preference for="Magento\Widget\Controller\Adminhtml\Widget\LoadOptions"
                type="CustomModule\CustomWidgets\Controller\Widget\Adminhtml\Widget\WidgetLoadOptions" />

    <preference for="Magento\Cms\Controller\Adminhtml\Wysiwyg\Images\OnInsert"
                type="CustomModule\CustomWidgets\Controller\Cms\Adminhtml\Wysiwyg\Images\WidgetOnInsert" />

</config>

After clear all generated folders (var/cache, var/di, var/generation) it works OK. The problem starts once I run magento setup:di:compile command. Compilation is executed successfully (tested in developer and production modes) but preference doesn't work (original Magento method is executed instead of mine).

Can someone help me? thanks in advance!

EDITED:

If someone has same issue, I have reported some time ago the issue in Magento 2 repository and they confirmed there was a bug:

https://github.com/magento/magento2/issues/5157

I will update the answer once they get it solved.

Best Answer

I may be wrong but I'm pretty sure it's because those controllers are admin controllers and thus the corresponding di.xml should not be global.

I reckon you should move your di.xml from etc to etc/adminhtml