How to inject custom dependence in custom entity? On Drupal 8, in a custom entity class, I'm trying to load a repository in the constructor to be able to use custom functions in the preSave().

class MyEntity extends ContentEntityBase implements MyModuleInterface {

private $customStuff;

public function __construct(array $values, $entity_type, &amp;$bundle = FALSE, $translations = []) {
        $this-&gt;customStuff = \Drupal::service('mymodule.mymodule_repository');
  }


(The service is defined in .services.yml in the correct module)

But I have the error :

The website encountered an unexpected error. Please try again later.Drupal\Component\Plugin\Exception\PluginNotFoundException: The &quot;&quot; entity type does not exist. in Drupal\Core\Entity\EntityTypeManager-&gt;getDefinition() (line 133 of core/lib/Drupal/Core/Entity/EntityTypeManager.php). Drupal\Core\Entity\EntityManager-&gt;getDefinition(NULL) (Line: 410)

How to inject custom dependence in custom entity ?
How to inject custom dependence in custom entity?


You cannot; per the Services and dependency injection documentation:


  Note: It's not possible to inject services to entity object. See this issue for more details.


You'll have to get the service from \Drupal directly.