Score:2

Difference between ContainerInjectionInterface and ContainerFactoryPluginInterface?

nl flag

Both ContainerInjectionInterface and ContainerFactoryPluginInterface provide a create() function and are used for dependency injection.

I would like a clear description of their differences and their use cases, such that it's clear which interface a class should implement.

  • Which should I use if I only need to use injected services in a class?
  • Which should I use in a service class that will be injected in other classes and defined in the module.services.yml?
Score:3
cn flag

The first one is typically used for controllers and the second one is for plugins. If you only need to inject services in service classes defined in module.services.yml you need neither of them.

mbomb007 avatar
nl flag
I just looked at Cron.php and its entry in core.services.yml, and it looks like a good example of how you don't need to implement one to inject services. So basically, you only need `ContainerFactoryPluginInterface` if you intend to inject your class into another class?
cn flag
No, you only need `ContainerFactoryPluginInterface` if you're creating a plugin. A basic service that can be injected into another class doesn't need to implement _any_ interfaces to get the DI working. The definition in services.yml provides that function. In reality all `ContainerFactoryPluginInterface` does is force the class to have a `create` method, which is provided the container as an argument, so you can instantiate a class with injected services. You already define those services in services.yml for a "normal" service, so no interface is needed
Jaypan avatar
de flag
Plugins don't by definition call the `create()` method, so there is no dependency injection. If you are creating a plugin that needs dependency injunction, you would declare `ContainerFactoryPluginInterface`.
mbomb007 avatar
nl flag
Thanks. After removing a bunch of needless `implements ContainerPluginInterface`, I don't need it anywhere. It's still used for controllers and forms, but in those cases you end up extending `ControllerBase` or `FormBase` and you don't need to add it yourself.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.