Magento – Magento 2 StoreManagerInterface already exists in context object in compilation

blockscompilationerrormagento-2.1magento2

I am getting this error in my extension.

PackageName\ModuleName\Block\Enhanced
Incorrect dependency in class PackageName\ModuleName\Block\Enhanced in
/var/www/html/app/code/PackageName/ModuleName/Block/Enhanced.php
\Magento\Store\Model\StoreManagerInterface already exists in context object

 public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\Session $catalogSession,
    \Magento\Store\Model\StoreManagerInterface $storeManager,        
    array $data = []

)
{
    parent::__construct($context, $data);
    $this->_catalogSession = $catalogSession;
    $this->_storeManager = $storeManager;      
}

Best Answer

You don't need to inject \Magento\Store\Model\StoreManagerInterface in your constructor because the parent class already does that.

I assume your block extends Magento\Framework\View\Element\Template which already has the following code:

protected $_storeManager;

public function __construct(Template\Context $context, array $data = [])
{
    $this->validator = $context->getValidator();
    $this->resolver = $context->getResolver();
    $this->_filesystem = $context->getFilesystem();
    $this->templateEnginePool = $context->getEnginePool();
    $this->_storeManager = $context->getStoreManager();
    $this->_appState = $context->getAppState();
    $this->templateContext = $this;
    $this->pageConfig = $context->getPageConfig();
    parent::__construct($context, $data);
}

Thus you can replace your code with:

public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Catalog\Model\Session $catalogSession,   
    array $data = []

)
{
    parent::__construct($context, $data);
    $this->_catalogSession = $catalogSession;
}
Related Topic